Search code examples
javaspringservletsdependency-injectionspring-annotations

Spring DI based on annotations


i try to use spring, and stuck with spring configuration. As you see in title i try to configure on annotations and also try to use spring-boot (which is very good as i think).

So my question is very simple (i think), is how to inject my bean to servlet (other class, etc.)

1) i have a configured application

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(applicationClass, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class<Application> applicationClass = Application.class;

    @Bean(name = "some", autowire = Autowire.BY_TYPE)
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public Some someInit() {
        return new Some();
    }
}

2) bean

public class Some {

    public Some() {}

    public Integer get() {
        return 1;
    }
}

3) and servlet where i try to inject my bean

public class IndexServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public IndexServlet() {
        super();
    }

    @Autowired
    Some some;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer integer = some.get();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

}

So, some is always null, and i don't understand why. I was tried to debug code, and i saw that Application is initialized and Some in Application is instantiated. But it is not injected to my servlet.

Thank you!


Solution

  • Well, i find the solution, put the code below in your Servlet

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }