簡體   English   中英

自動裝配的Bean在線程位置為null

[英]Autowired bean is null in thread location

如何從線程訪問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”類中,您正在使用的不是自動裝配屬性“ protected ExampleService exampleService”,這是沒有@Autowired注釋的屬性。 @ Service,@ Controller,@ Repository和@Component

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM