gpt4 book ai didi

Spring 未将 bean 注入(inject)线程

转载 作者:行者123 更新时间:2023-12-03 03:49:45 25 4
gpt4 key购买 nike

1.如何将spring bean注入(inject)线程

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方法(请建议我是否遵循错误的方法来调用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 类执行依赖注入(inject)

最佳答案

您的设置存在一些问题。

  1. 您不应该自己创建和管理线程,Java 有很好的功能可以使用这些线程。
  2. 您自己创建新的 bean 实例并期望 Spring 了解它们并注入(inject)依赖项,这是行不通的。

Spring 提供了执行任务的抽象, TaskExecutor 。您应该配置一个并使用它来执行您的任务,而不是自己创建线程。

将其添加到您的@Configuration 类中。

@Bean
public ThreadPoolTaskExecutor taskExecutor() {
return new ThreadPoolTaskExecutor();
}

您的MyThread应使用@Scope("prototype")进行注释。

@Component
@Scope("prototype")
public class MyThread implements Runnable { ... }

现在您可以将这些 bean 和 ApplicationContext 注入(inject)到您的 MyServiceCreationListener

@Component
public class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {

@Autowired
private ApplicationContext ctx;
@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 上执行它。

关于Spring 未将 bean 注入(inject)线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com