Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Spring autowiring for a certain bean?

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

@Component
public class TestBean {

    @Autowired
    private TestDependency dependency;

    ...
}

And library provides API for constructing objects:

public class Library {

    public static TestBean createBean() {
        ApplicationContext context = new AnnotationConfigApplicationContext(springConfigs);
        return context.getBean(TestBean);
    }
}

In my application, I have config:

@Configuration
public class TestConfig {

    @Bean
    public TestBean bean() {
        return Library.createBean();
    }
}

It's throw en exception: Field dependency in TestBean required a bean of type TestDependency that could not be found..

But Spring should not trying to inject something, because bean is already configured.

Can i disable Spring autowiring for a certain bean?

like image 696
sata Avatar asked Jan 26 '17 18:01

sata


People also ask

How do you exclude a bean from being available for Autowiring?

If you are using Spring XML configuration then you can exclude a bean from autowiring by setting the autowire-candidate attribute of the <bean/> element to false. That way container makes that specific bean definition unavailable to the autowiring infrastructure.

How do I exclude a bean?

You need a method with '@Bean' annotation that crate and instance of the class, or annotate the class with '@Componen', '@Service' etc. annotation for annotation scanning to find it ? Does @ComponentScan(excludeFilters = @ComponentScan.

How do I stop Autowired?

You can just remove the @Autowired annotation from the constructor and it will still work (if you're not using a really old version of Spring).

How do you turn off Spring beans?

In Spring Boot, you can use the @ConditionalOnProperty annotation to enable or disable a particular bean based on the presence of a property. This is very useful if you want to provide optional features to your microservice. And that's it. Your optionalClass bean should resolve to null when you specify mybean.


1 Answers

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());
}
like image 176
Alexey Avatar answered Sep 19 '22 20:09

Alexey