There are some class in jar (external library), that uses Spring internally. So library class has structure like a:
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;
...
}
Not exactly but you can add required=false (@Autowired(required=false))
in your autowired annotation. But be careful that might get you NullPointer exception
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;
}
};
}
}
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());
}