如何从线程访问exampleService?在新线程中为null。 ExampleService是带注释的@Service类。 SessionFactory我是从dao设置的,它不是null。
public class ExampleInterceptor extends EmptyInterceptor {
private Logger logger = Logger.getLogger(getClass());
private static final long serialVersionUID = 1L;
@Autowired
SessionFactory sessionFactory;
@Autowired
ExampleService exampleService;
public void setExampleService(ExampleService exampleService) {
this.exampleService = exampleService;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void afterTransactionCompletion(Transaction tx) {
new Thread(new SimpleThread(exampleService)).start();
}
protected class SimpleThread implements Runnable {
protected ExampleService exampleService;
public SimpleThread() {
};
public SimpleThread(ExampleService exampleService) {
this.exampleService = exampleService;
}
@Override
public void run() {
exampleService.method(); // is null at this location
}
}
}
答案 0 :(得分:1)
您需要使用@Service注释服务类,并且要使用该对象,您需要自动装配它。 如果我没有错,请在你的" SimpleThread"上课时,您使用的不是自动装配物业 " protected ExampleService exampleService",它没有@Autowired注释。 @Service, @Controller, @Repository & @Component