基于注释的弹簧DI
问题描述:
我尝试使用弹簧,并卡住弹簧配置。正如你在标题中看到的,我尝试在注释上进行配置,并尝试使用spring-boot(这是非常好的,因为我认为)。基于注释的弹簧DI
所以我的问题很简单,(我认为),是如何注入我的豆与Servlet(其他类等)
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)和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 {
}
}
所以,有些总是空的,我不明白为什么。我试图调试代码,并且我看到Application被初始化,并且Some in Application被实例化。但它不会被注入到我的servlet中。
谢谢!
答
好了,我找到解决方案,把下面的代码在你的servlet
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}