How to disable Spring autowiring for a certain bean?

前端 未结 4 925
天命终不由人
天命终不由人 2020-12-15 22:39

There are some class in jar (external library), that uses Spring internally. So library class has structure like a:

         


        
相关标签:
4条回答
  • 2020-12-15 23:02

    It seems like it's impossible to disable autowiring for a specific bean.

    So there is some workaround. We can make wrapper for a target bean and use it instead of original bean:

    public class TestBeanWrapper {
    
        private final TestBean bean;
    
        public TestBeanWrapper(TestBean bean) {
            this.bean = bean;
        }
    
        public TestBean bean() {
            return bean;
        }
    }
    
    @Configuration
    public class TestConfig {
    
        @Bean
        public TestBeanWrapper bean() {
            return new TestBeanWrapper(Library.createBean());
        }
    }
    
    @RestController
    public class TestController {
    
        @Autowired
        private TestBeanWrapper bean;
    
        ...
    }
    
    0 讨论(0)
  • 2020-12-15 23:03

    Not exactly but you can add required=false (@Autowired(required=false)) in your autowired annotation. But be careful that might get you NullPointer exception

    0 讨论(0)
  • 2020-12-15 23:07

    This worked for me:

    import org.springframework.beans.factory.FactoryBean;  
    ...  
    @Configuration
    public class TestConfig {
    
        @Bean
        public FactoryBean<TestBean> bean() {
            TestBean bean = Library.createBean();
    
            return new FactoryBean<TestBean>()
            {
                @Override
                public TestBean getObject() throws Exception
                {
                    return bean;
                }
    
                @Override
                public Class<?> getObjectType()
                {
                    return TestBean.class;
                }
    
                @Override
                public boolean isSingleton()
                {
                    return true;
                }
            };
        }
    }
    
    0 讨论(0)
  • 2020-12-15 23:23

    Based on @Juan's answer, created a helper to wrap a bean not to be autowired:

    public static <T> FactoryBean<T> preventAutowire(T bean) {
        return new FactoryBean<T>() {
            public T getObject() throws Exception {
                return bean;
            }
    
            public Class<?> getObjectType() {
                return bean.getClass();
            }
    
            public boolean isSingleton() {
                return true;
            }
        };
    }
    
    ...
    
    @Bean
    static FactoryBean<MyBean> myBean() {
        return preventAutowire(new MyBean());
    }
    
    0 讨论(0)
提交回复
热议问题