简体   繁体   English

如果我在一个类的成员上使用Spring的@Autowired注释,我可以在课堂上新建吗?

[英]If I use Spring's @Autowired annotation on a member of a class, can I new up the class?

I have a dependent class B of class A that I want injected into A . 我有一个A类的依赖类B ,我想要注入A

And so I use the @Autowired annotation in class A . 所以我在A级使用@Autowired注释。 But class A itself I create using new keyword and I find that the reference to class B is null . 但是我使用new关键字创建了A类,我发现对B类的引用是null

So if you are using Autowired , must Spring manage class A also? 因此,如果您使用的是Autowired ,那么Spring也必须管理A类吗?

I mean, is the null reference because I am using new and not letting Spring manage the whole thing? 我的意思是,是null引用,因为我使用new并且不让Spring管理整个事情?

Yes, the both classes need to be in the same context. 是的,这两个类需要在同一个上下文中。 Manage by Spring. 由Spring管理。

You can see an example here. 你可以在这里看到一个例子。 http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/ http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

是的,Spring容器应该管理A类和B类的对象,以便能够将B引用注入A.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM