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 …Run Code Online (Sandbox Code Playgroud) 我想在 spring 应用程序中运行一个线程
@Component
public class MyServiceCreationListener {
public void startThread() {
Thread t = new Thread(new MyThread());
t.start();
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里使用Thread t = new Thread(new MyThread());这是错误的方式。
请为此提供解决方案,以便像 spring bean 一样 spring 管理 MyThread,以便我们可以将其自动装配到其他 bean 中,并通过调用start()方法我们可以访问它
这是线程类
@Component
public class MyThread implements Runnable {
public void run() {
System.out.println("Inside run()");
}
}
Run Code Online (Sandbox Code Playgroud) java multithreading dependency-injection spring-mvc autowired