我尝试使用弹簧,并坚持使用弹簧配置。正如你在标题中看到的那样,我尝试配置注释,并尝试使用spring-boot(我认为这非常好)。
所以我的问题很简单(我认为),是如何将我的bean注入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)bean
public class Some {
public Some() {}
public Integer get() {
return 1;
}
}
3)和servlet,我尝试注入我的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 {
}
}
所以,有些总是空的,我不明白为什么。我试图调试代码,我看到应用程序已初始化,应用程序中的某些实例化。但它没有注入我的servlet。
谢谢!
答案 0 :(得分:0)
好吧,我找到了解决方案,将下面的代码放在你的Servlet中
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}