Spring MVC 中整数(最终类)的 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);
}
}
I need such a usage:
For each request I want to inject userId into DemoController But because of being a final class without empty constructor I can not inject it. What is the best practice in such cases? A service with request scope is fine?
@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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的选择是创建一个名为
UserId
的显式类,该类又包含一个整数。这不仅可以更好地配合 CGLIB 的代理,而且还可以澄清您的设计。Your best bet is to create an explicit class called
UserId
, which in turn contains an integer. Not only will this play nicer with CGLIB's proxying, it also clarifies your design.您可以使用供应商或提供商
You can use Supplier or Provider