[英]Spring Dependency Injection of nested beans
I'm fighting with Spring Dependency Injection and nested beans: There are two beans and one of them is nested in the other. 我正在与Spring Dependency Injection和嵌套bean进行斗争:有两个bean,其中一个嵌套在另一个中。 When inspecting the outer bean, I can see, that the inner bean isn't injected.
在检查外部bean时,我看到没有注入内部bean。
The main class: 主班:
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx
= new AnnotationConfigApplicationContext("org.acme");
MyService myService = ctx.getBean(MyService.class);
// do something with myService
}
}
The outer bean: 外层豆:
@Component
public class MyService {
@Inject // javax.inject.Inject
private MyDao dao;
public MyService() {
System.out.println(dao);
}
}
The inner bean: 内部bean:
@Component
public class MyDao {
public MyDao() {
System.out.println("dao is alive");
}
}
There is no error when starting the application, but I see null
getting printed out by the constructor of MyService
and dao is alive
. 启动应用程序时没有错误,但是我看到
MyService
的构造函数将null
打印出来,并且dao is alive
。 I had the same issue when trying with a @Configuration
class. 尝试使用
@Configuration
类时,我遇到了同样的问题。 It seems like the outer beans depedencies won't be injected. 似乎不会注入外部bean的依赖。
Thx! 谢谢!
I made it work with constructor injection . 我使它与构造函数注入一起使用 。
@Component
public class MyService {
private MyDao dao;
@Inject // javax.inject.Inject
public MyService(MyDao dao) {
System.out.println(dao);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.