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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...