简体   繁体   English

如何在线程中注入Spring Bean

[英]How to inject Spring Bean in thread

I have a running Spring 3 web application. 我有一个正在运行的Spring 3 Web应用程序。 All the beans are correctly injected and everything is working as it should (all web service calls are working properly). 所有Bean均已正确注入,并且一切都按预期进行(所有Web服务调用均正常工作)。

While expanding the application I needed to add threads that can be started & stopped via a web service. 在扩展应用程序时,我需要添加可以通过Web服务启动和停止的线程。

In the thread I need to inject some Spring beans. 在线程中,我需要注入一些Spring bean。 These beens are services (annotated with @Service). 这些更新是服务(以@Service注释)。 In my applicationContext the beans are detected via a component scan: 在我的applicationContext中,通过组件扫描检测到Bean:

<context:component-scan base-package="<package>">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

But when I try to inject the beans (using @Resource) in the thread they are always 'null' (Spring doesn't inject them). 但是,当我尝试将线程(使用@Resource)注入bean时,它们始终为“ null”(Spring不会注入它们)。 The thread is started but fails while initializing. 线程已启动,但初始化时失败。

I also tried injecting them by loading the applicationContext in code: (application context is located in 'src/main/resources') 我还尝试通过在代码中加载applicationContext来注入它们:(应用程序上下文位于“ src / main / resources”中)

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:*applicationContext.xml");

if(applicationContext.containsBean("BeanName")) {

        beanObject = (BeanClass) applicationContext.getBean("BeanName");

} else {

    //Exception
}

Does anyone have any idea how to inject the beans in the thread? 有谁知道如何在线程中注入bean? Or isn't it possible to inject beans in a thread? 还是不可能在线程中注入bean?

Thanks in Advance! 提前致谢!

It would be better to separate business logic (the code that depends on your services) from the infrastructure code that manages threads. 最好将业务逻辑(取决于您的服务的代码)与管理线程的基础结构代码分开。

For example, you can declare a bean that implements Runnable for your business logic and then use it when you need to start a Thread . 例如,您可以声明一个为您的业务逻辑实现Runnable的bean,然后在需要启动Thread时使用它。

However, starting Thread s manually is not a good practice as well. 但是,手动启动Thread也不是一个好习惯。 It would be better to use thread pools instead. 最好改用线程池。 Actually, Spring provides some built-in support for thread pools and asynchronous execution, so that you can leverage it, see 25. Task Execution and Scheduling . 实际上,Spring为线程池和异步执行提供了一些内置支持,因此您可以利用它,请参见25.任务执行和调度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM