Optional Spring bean references

后端 未结 5 2095
逝去的感伤
逝去的感伤 2020-12-03 17:22

In my application I am using ContextLoaderListener to load context files from many jars using:


    contextConfigLocat         


        
5条回答
  •  醉梦人生
    2020-12-03 17:26

    what method do you recommend for handling dynamic references?

    I think @cristian's @Autowired answer is a good one. That will call the setter methods if the beans of that type are available. However, if you have multiple beans of the same type, I believe Spring throws an exception. If you cannot use @Autowired for this or some other reason, I see a couple of solutions:

    1. You could make your class ApplicationContextAware and lookup the beans in the context yourself:

      public void setApplicationContext(ApplicationContext applicationContext) {
          if (applicationContext.containsBean("optionalBeanReference1")) {
              setOptionalBeanReference1(
                  (OptionalBeanReference1)applicationContext.bean(
                      "optionalBeanReference1");
          }
          ...
      }
      
    2. You could invert the dependency. Each of the optional classes could set themselves on the mainAppBean. I use this in certain situations when a direct dependency would cause loops or other problems.

      
          
      
      

      Then in the SomeClass:

      public SomeClass(com.someapp.MyApplication mainAppBean) {
          mainAppBean.setOptionalBeanReference1(this);
      }
      
    3. You could stay with your direct dependency and then either import a file with the beans defined or import another file where you define the beans as having null values by using a factory bean. See this factory code.

    Good luck.

提交回复
热议问题