Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...