如何从线程访问exampleService?在新线程中为null。 ExampleService是带注释的@Service类。我从dao设置的SessionFactory,它不是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
        }

    }

}

最佳答案

您需要使用@Service注释服务类,并且要使用该对象,需要对其进行自动装配。
如果我没看错,在您的“ SimpleThread”类中,您正在使用不自动装配属性
“受保护的ExampleService exampleService”,它没有@Autowired批注。
@Service, @Controller, @Repository & @Component

09-20 23:48