Singleton and @Autowired returning NULL

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

    
    

    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.

提交回复
热议问题