The problem has been solved, but will still be recorded.
public class PnFileTGIComputeThread implements Runnable { @Resource private AppUsedService appUsedService;// AppUsedService appUsedService = (AppUsedService) AllBean.getBean("appUsedService"); public String taskId; public int cityId; public PnFileTGIComputeThread(String name, int cityId){ this.taskId = name; this.cityId = cityId; } @Override public void run() { try { this.appUsedService .doSaveAzTaskAppUsedInfoCity(Integer.valueOf(taskId),cityId); } catch (Exception e){ e.printStackTrace () ; } } }A new thread is created, and then the thread is instantiated in the main thread to start the thread. The DUG problem is that after the thread is started, the parameters are also passed, but the service injected through the annotation is always the null value.
The old method is to flip over the brand of Du Niang and find the problem. For thread safety, it is anti-injection in the thread. No way, use this class. You can only get an instance from the bean factory
public class AllBean implements ApplicationContextAware{ private static ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext context) { AllBean.applicationContext = context; } public static Object getBean(String name){ return applicationContext.getBean(name); } public static ApplicationContext getApplicationContext() { return applicationContext; } }getbean method, get the bean in the context, but there is a problem, this AllBean class needs to be registered in the Bean factory
<bean id="allBean" class="xxxxx.AllBean" />If you want anything, you can go directly to getBean now, for example:
AppUsedService appUsedService = (AppUsedService) AllBean.getBean("appUsedService");
OK, the thread started normally.