小编suh*_*s_n的帖子

Spring没有将bean注入线程

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 multithreading dependency-injection

4
推荐指数
1
解决办法
6080
查看次数

如何在 Spring bean 中启动线程

我想在 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

3
推荐指数
1
解决办法
8853
查看次数