Spring in multi-threading, bean injection problem (transfer to blog garden)

Spring in multi-threading, bean injection problem

I encountered a problem recently. Using the SSM framework, another thread needs to be opened in the Service layer. This thread is specially used to do some operations and write the results to the database. However, using @Resource or @Autowired injection in a thread is all NULL .
It turns out that Spring cannot inject in a thread.

The main solutions online are:

  1. Pass the required Bean as a parameter of the thread's constructor
  2. Use the ApplicationContext.getBean method to obtain beans statically

The number of beans required in my thread is large, and it may increase or decrease in the future, so method 1 is not suitable for
my Spring configuration file and there is not only one, and using the getBean method needs to reload all beans, so Also violates Spring's IoC, not what I want, so I don't use method 2

Finally, it is determined to use the method of the inner class to inject the beans needed in the thread in advance. The general structure is as follows:

@Service
class TestExample{

    //这两个为线程所需要的Bean
    @Resource
    TestDao testDao;

    @Resource
    NeedDap needDao;

    public void serviceExecute(){
        //在这里开启线程,执行操作
        ThreadExample te = new ThreadExample();
        te.start();
    }
    
    //内部类
    private class ThreadExample extends Thread{

        public ThreadExample(){
            //也可以在构造函数中传入参数
        }
        public void run(){
            //这里为线程的操作
            //就可以使用注入之后Bean了

        }
    }
}

https://www.cnblogs.com/bencakes/p/6139542.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325647790&siteId=291194637