Singleton and @Autowired returning NULL

后端 未结 4 492
难免孤独
难免孤独 2021-01-02 07:21

I have a repository manager that manages my repositories. I have the @Autowired to instantiate my properties, but they are always null. The beans are correctly configured

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 07:38

    I just ran into this myself. The problem is that when you do

    new RepositoryManager();
    

    in Instance(), you are not using Spring to create RepositoryManager, and thus the dependency injection isn't happening for your instance (no autowiring).

    The solution is to do away with the Instance() singleton pattern. If you want to insist on a Singleton, then do this

    @Component
    @Scope(value = "singleton")
    public class RepositoryManager {
        ...
    }
    

    Then wherever you need the repository manager, just autowire in a reference to it (assuming the calling bean is also managed by Spring!)

    @Autowired
    private RepositoryManager repositoryManager = null;
    

提交回复
热议问题