suh*_*s_n 4 spring multithreading dependency-injection
1.如何将弹簧豆注入螺纹中
2.如何在spring bean中启动一个线程.
这是我的代码.
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 Code Online (Sandbox Code Playgroud)
我正在run从下面的类调用方法(请建议我是否遵循错误的appraoch调用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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
spring没有在MyThread类上执行依赖注入
您的设置存在一些问题.
Spring提供了一个执行任务的抽象,TaskExecutor.您应该配置一个并使用它来执行您的任务而不是自己创建一个线程.
将此添加到您的@Configuration班级.
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
return new ThreadPoolTaskExecutor();
}
Run Code Online (Sandbox Code Playgroud)
你MyThread应该注明@Scope("prototype").
@Component
@Scope("prototype")
public class MyThread implements Runnable { ... }
Run Code Online (Sandbox Code Playgroud)
现在你可以将这些豆子ApplicationContext注入你的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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个预先配置的新实例,MyThread并在手边Thread选择执行它TaskExecutor.
| 归档时间: |
|
| 查看次数: |
6080 次 |
| 最近记录: |