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
365 views
in Technique[技术] by (71.8m points)

java - Java Spring Bean依赖项注入conditionalOnBean(Java Spring Bean dependency injection, conditionalOnBean)

Attempting to create a class that will be used by JavaConfig as a source of bean definitions.

(尝试创建一个将由JavaConfig用作bean定义源的类。)

@Configuration
public class MyClass {
    @Bean
    @ConditionalOnProperty(name = "property")
    public A fuction1() {
       doSomething1(); // may return an exception
    }

    @Bean
    @ConditionalOnMissingBean(name = "fuction1")
    public A fuction2() {
        doSomething2();
    }

    @Bean
    public B fuction3(A a) {
        doSomething3(a);
    }
}

The third bean definition has the error "could not autowire. There is more than one bean of A type."

(第三个bean定义具有错误"could not autowire. There is more than one bean of A type.")

How do I tell Spring to try to autowire the first A and if it is missing then to try the second A, ie following the conditional process described.

(我如何告诉Spring尝试自动连接第一个A,如果缺少它,然后尝试第二个A,即遵循所述的条件过程。)

Hopefully that makes sense.

(希望这是有道理的。)

Thanks!

(谢谢!)

  ask by Chris Johnston translate from so

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

1 Answer

0 votes
by (71.8m points)

You are defining two bean with same name hence, autowiring issue is obvious.

(您要定义两个具有相同名称的bean,因此,自动装配问题显而??易见。)

Try using @Primary on the bean you want to give priority.

(尝试在要赋予优先级的bean上使用@Primary 。)


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

...