java - spring boot @Autowired
阿神
阿神 2017-04-18 10:56:21
0
4
774

如何在一个没有注解的类中加入一个已经注解的@Autowired?

classA 没有添加xml也没有注解到spring中

classB @Component 已经加入注解

如何在classA 中用@Autowired 注解classB?

如果classA也 @Component了,classB可用,但是不注解就会报错。

阿神
阿神

闭关修行中......

reply all(4)
伊谢尔伦

Make a SpringContextHolder

Peter_Zhu

@Component is a bean type annotation of spring. Only after adding this annotation will the bean be managed by spring. If this annotation is not added, spring will not be able to recognize this class, so an error will be reported. If this annotation is added, Then spring knows that these two classes are two beans in spring and can automatically inject each other. My understanding of spring is not deep enough, what I said may be wrong, it is just my personal opinion

黄舟

Get it from applicationContext using service name.

左手右手慢动作

@Autowired means injection. To use injection, your class must be managed by spring, which means your class B必须是是一个spring的bean, class A也必须是一个spring的bean, 你报错就是因为你的class A不是一个spring的bean, spring无法帮你注入class B.
如果要在不是spring bean的class A中使用class B只能手动把class Bset is put in.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template