Intentionally setting a Spring bean to null

后端 未结 7 1947
孤独总比滥情好
孤独总比滥情好 2020-12-05 06:32

I\'m using Spring to inject JMS connection factory into my Java application. Since this factory is only required within the production environment, not while I\'m developing

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 07:26

    Some noted above, axtact's answer doesn't work in Autowiring contextes, where Spring will rely on correct information from the getObjectType() method. So you might end up with errors like:

    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [xxxxxxxxxxxxx] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=yyyyyyyyyyyyyyyy)}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotatio
    

    So here's a small variation which involves allowing users to force the objectype at construction. Using a property instead of a constructor-arg didn't work because Spring doesn't fully initialize the beans in this context.

    public class NullFactoryBean implements FactoryBean {
        private final Class objectType;
    
        public NullFactoryBean(Class objectType) {
            this.objectType = objectType;
        }
    
        @Override
        public Object getObject() throws Exception {
            return null;
        }
    
        @Override
        public Class getObjectType() {
            return objectType;
        }
    
        @Override
        public boolean isSingleton() {
            return false;
        }
    }
    

提交回复
热议问题