Spring 基于注解的DI

Spring DI based on annotations

我尝试使用 spring,并坚持使用 spring 配置。正如您在标题中看到的,我尝试配置注释并尝试使用 spring-boot(我认为这非常好)。

所以我的问题很简单(我认为),就是如何将我的 bean 注入到 servlet(其他 class 等)

1) 我有一个已配置的应用程序

@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) 豆子

public class Some {

    public Some() {}

    public Integer get() {
        return 1;
    }
}

3) 和我尝试注入 bean 的 servlet

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 {
    }

}

所以,some 总是空的,我不明白为什么。我试图调试代码,我看到 Application 已初始化并且 Application 中的 Some 已实例化。但是它没有注入我的servlet。

谢谢!

好吧,我找到了解决方案,将下面的代码放入您的 Servlet

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