Spring没有将bean注入线程 [英] Spring not injecting a bean into thread
问题描述
1.如何将Spring bean注入线程
1.How to inject a spring bean into thread
2.如何在spring bean中启动线程.
2.How to start a thread inside spring bean.
这是我的代码.
MyThread.java
MyThread.java
@Component
public class MyThread implements Runnable {
@Autowired
ApplicationContext applicationContext;
@Autowired
SessionFactory sessionFactory;
public void run() {
while (true) {
System.out.println("Inside run()");
try {
System.out.println("SessionFactory : " + sessionFactory);
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(10000);
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我正在从下面的类中调用run
方法,例如(请提出建议,如果我遵循错误的方法来调用spring bean中的线程)
i am calling run
method from below class like (Please suggest if i am following wrong appraoch for calling a thread inside spring bean )
@Component
public class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
System.out.println("\nThread Started");
Thread t = new Thread(new MyThread());
t.start();
}
}
}
spring不在MyThread
类
推荐答案
设置有几处错误.
- 您不应该自己创建和管理线程,Java具有使用这些线程的不错的功能.
- 您要自己创建新的bean实例,并希望Spring知道它们并注入依赖项,但这是行不通的.
Spring提供了执行任务的抽象, TaskExecutor
.您应该配置一个并使用它来执行任务,而不要自己创建线程.
Spring provides an abstraction to execute tasks, the TaskExecutor
. You should configure one and use that to execute your task not create a thread yourself.
将此添加到您的@Configuration
类中.
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
return new ThreadPoolTaskExecutor();
}
您的MyThread
应该用@Scope("prototype")
注释.
@Component
@Scope("prototype")
public class MyThread implements Runnable { ... }
现在您可以将这些bean和ApplicationContext
注入到MyServiceCreationListener
Now you can inject these beans and an ApplicationContext
into your MyServiceCreationListener
@Component
public class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private ApplicationContext cox;
@Autowired
private TaskExecutor taskExecutor;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
System.out.println("\nThread Started");
taskExecutor.execute(ctx.getbean(MyThread.class));
}
}
}
这将为您提供预配置的MyThread
的新实例,并在手边的TaskExecutor
选择的Thread
上执行它.
This will give you a pre-configured, fresh instance of MyThread
and execute it on a Thread
selected by the TaskExecutor
at hand.
这篇关于Spring没有将bean注入线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!