why can I autowire or inject pojo but I can't autowire or inject RestTemplate

前端 未结 1 826
北海茫月
北海茫月 2021-01-26 13:28

I read a lot in this forum about similiar problems happening when trying to Autowire a pojo and usually the answer to fix is related to component-scan or @Com

相关标签:
1条回答
  • 2021-01-26 14:21
    private void doDisDis(HttpServletRequest request,HttpServletResponse response){
        Lo_DisplayHandler display = null;
        try {
            display = new Lo_DisplayHandler(request,response);
            display.lastPage();
        }catch(Exception e){
        }finally{
            display = null;
        }
    }
    

    The code above is creating new instances of the Lo_DisplayHandler class. Those instances aren't managed by Spring, so basically the @Autowired is pretty useless here. Spring will only do dependency injection into beans it knows.

    Assuming that you are using the ContextLoaderListener to load the spring configuration you can use the WebApplicationContextUtils to get the ApplicationContext. You can use this to get the beans you want.

    private void doDisDis(HttpServletRequest request,HttpServletResponse response){
        Lo_DisplayHandler display = null;
        try {
            ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());          
            display = context.getBean(Lo_DisplayHandler.class, request, response);
            display.lastPage();
        }catch(Exception e){
        }finally{
            display = null;
        }
    }
    

    To make this work you have to make your Lo_DisplayHandler a prototype bean, this means each time a getBean call is done a new instance is created. For this add the @Scope annotation to the class.

    @Component
    @Scope("prototype")
    public class Lo_DisplayHandler extends Lo_Handler { ... }
    

    A final note instead of doing a lookup for the ApplicationContext each time you need one, you might want to do it once in the init method of the servlet and store it as an instance variable. Saves you a line of code and some performance.

    0 讨论(0)
提交回复
热议问题