[英]CGLib Proxy for Integer (Final class) in Spring MVC
我需要這樣的用法:
對於每個請求,我想將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);
}
}
最好的選擇是創建一個名為UserId
的顯式類,該類又包含一個整數。 這不僅可以與CGLIB的代理搭配使用,而且可以澄清您的設計。
您可以使用供應商或提供商
@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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.