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?
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.
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.
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).
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With