Spring java配置中自动连线依赖项的注入失败
我是春天的新手。我正在测试Spring java配置中自动连线依赖项的注入失败,spring,Spring,我是春天的新手。我正在测试@Inject注释。为此,我创建了一个逻辑: import javax.inject.Inject; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.a
@Inject
注释。为此,我创建了一个逻辑:
import javax.inject.Inject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class A {
int a;
public A(int a) {
this.a = a;
}
}
class B {
A x;
public B(A x) {
this.x = x;
}
}
@Configuration
class config1 {
A a;
@Inject
public void setA(A a) {
this.a = a;
}
@Bean
public B getB() {
return new B(a);
}
}
@Configuration
class config2 {
@Bean
public A getA() {
return new A(4);
}
}
public class Testt {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(config1.class);
B oa = ctx.getBean(B.class);
System.out.println(oa.x.a);
}
}
但这失败了,错误是:
Error creating bean with name 'config1': Injection of autowired dependencies failed;
请帮忙。我知道我犯了一些小错误。您仅用一个类初始化了上下文:
new AnnotationConfigApplicationContext(config1.class)
您需要告诉Spring使用第二类
您可以添加第二类:
new AnnotationConfigApplicationContext(config1.class, config2.class)
或在config1中添加导入
@Import({config2.class})
请共享完整的异常或stacktrace,这可能会有所帮助。您在这里试图实现什么?