Spring MVC中的CGLib Proxy for Integer(Final class)

时间:2011-02-18 11:29:19

标签: java spring spring-mvc spring-aop cglib

我需要这样的用法:

对于我想将userId注入DemoController的每个请求但由于是没有空构造函数的最终类,我无法注入它。在这种情况下,最佳做法是什么?请求范围的服务很好吗?

@Configuration
public class CityFactory{

   @Bean(name = {"currentUserId")
   @Scope(value = WebApplicationContext.SCOPE_REQUEST,proxyMode = ScopedProxyMode.TARGET_CLASS)
   @Autowired
   public Integer getUserId(HttpServletRequest request) {
       return UserUtil.getCurrentUserId(request.getServerName());
   }
}


@RequestMapping("/demo")
@Controller
public class DemoController {

    @Autowired
    Ingeter userId;

    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    public ModelAndView helloWorld(@PathVariable("name") String name, Model model) {
        Map<String, Object> myModel = new HashMap<String, Object>();
        model.addAttribute("user", userId);
        return new ModelAndView("v3/test", "m", model);
    }
}

2 个答案:

答案 0 :(得分:3)

最好的办法是创建一个名为UserId的显式类,它又包含一个整数。这不仅可以通过CGLIB的代理更好地发挥作用,还可以澄清您的设计。

答案 1 :(得分:0)

您可以使用供应商或提供商

@Configuration
public class CityFactory{

   @Bean
   @Autowired
   public Supplier<Integer> getUserId(HttpServletRequest request) {
       return () -> UserUtil.getCurrentUserId(request.getServerName());
   }
}
@RequestMapping("/demo")
@Controller
public class DemoController {

    @Autowired
    Supplier<Ingeter> getUserId;