Singleton and @Autowired returning NULL

后端 未结 4 493
难免孤独
难免孤独 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:31

    Please make sure that you have the following in your config:

    <context:annotation-config />
    
    <context:component-scan base-package="name.of.your.package"></context:component-scan>
    

    If you have it then post your configuration xml

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-01-02 07:51

    There is actually a very elegant way to have your cake and eat it, i.e., have a JVM singleton that's also Spring-managed. Say you have a pure java singleton with an autowired bean like this:

    public final class MySingletonClass{
      private static MySingletonClass instance;
    
      public static MySingletonClass getInstance(){
        if(instance==null){
          synchronized{
            if(instance==null){
              instance = new MySingletonClass();
            }
          }
        }
        return instance;
      }
    
      @Autowired
      private SomeSpringBean bean;
    
      // other singleton methods omitted
    }
    

    You can force Spring to manage this singleton simply by adding in your application context the following line:

    <bean class="com.mypackage.MySingletonClass" factory-method="getInstance"/>
    

    Now your singleton will have an instance of SomeSpringBean autowired (if available in the context).

    Moreover, this is a 'fix' for the typical problem with Spring singleton beans that are not truly JVM singletons because they get instantiated by Spring. Using the pattern above enforces JVM level singleton, i.e., compiler enforced singleton, together with container singleton.

    0 讨论(0)
  • 2021-01-02 07:51

    The reason this is happening is because of the static method Instance()

    you are creating the POJO outside of the spring context.

    you can fix this, by adding <context:spring-configured /> to your configuration, and then annotating RepositoryManager with @Configurable

    0 讨论(0)
提交回复
热议问题