Spring injection Into Servlet

后端 未结 4 1820
Happy的楠姐
Happy的楠姐 2020-11-29 21:17

So I have seen this question:

Spring dependency injection to other instance

and was wondering if my method will work out.

1) Declare beans in my Spri

4条回答
  •  孤街浪徒
    2020-11-29 21:45

    The answers here so far only worked partly for me. Especially classes with @Configuration annotation were ignored and I did not want to use an xml configuration file. Here is what I have done to get injection working working soley with an Spring (4.3.1) annotation based setup:

    Bootstrap an AnnotationConfigWebApplicationContext in web.xml under web-app. As parameter you need the contextClass and the contextConfigLocation (your annotated config class):

    
        contextClass
        
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      
    
    
        contextConfigLocation
        com.example.config.AppConfig
    
    
        org.springframework.web.context.ContextLoaderListener
    
    

    Then overwrite the init method in the servlet. I use an abstract class which extends HttpServlet, so I don't have to repeat it in every servlet:

    @Configurable
    public abstract class MySpringEnabledServlet extends HttpServlet
    {
      @Override
      public void init(
          ServletConfig config) throws ServletException
      {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
      }
    [...]
    }
    

    and finally I have my main configuration in the AppConfig class mentioned in web.xml:

    @Configuration
    @ComponentScan(basePackages = "com.example")
    @Import(
    { SomeOtherConfig.class })
    public class AppConfig
    {
    }
    

    The dependend classes are annotated:

    @Component
    public class AnnotatedClassToInject
    

    and injected via autowiring in my servlet:

    @Autowired
    private AnnotatedClassToInject myClass;
    

提交回复
热议问题