2015-02-09 104 views
-2

我嘗試使用彈簧,並卡住彈簧配置。正如你在標題中看到的,我嘗試在註釋上進行配置,並嘗試使用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中。

謝謝!

回答

0

好了,我找到解決方案,把下面的代碼在你的servlet

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