[英]How to refer a bean declared in spring context xml from an annotated class spring
Example: 例:
spring context xml 春天上下文xml
<beans>
<bean id="a" class="ClassA" />
</beans>
@Service public class Test { @Service公共类测试{
@Resource InterfaceA ifcA; @Resource InterfaceA ifcA;
} }
public class ClassA implements InterfaceA { } 公共类ClassA实现InterfaceA {}
public interface InterfaceA { } 公共接口InterfaceA {}
I would like to know how I can refer to xml bean declared in xml from a java class that has annotations enabled. 我想知道如何从启用了注释的Java类中引用xml中声明的xml bean。
One way I know would be get the context and then get the bean. 我知道的一种方法是获取上下文,然后获取bean。
Please suggest. 请提出建议。
In your annotated class, declare this 在带注释的类中,声明此
@Autowired InterfaceA ifcA;
Spring will automatically populate with the appropriate bean instance. Spring将自动使用适当的bean实例进行填充。
Your code should work out of the box since Spring takes care of @Resource annotations as well. 您的代码应该开箱即用,因为Spring也会处理@Resource批注。 It looks up the corresponding bean by the requested type (that's why it's called "autowiring by type"). 它按请求的类型查找相应的bean(这就是为什么将其称为“按类型自动装配”)。
You may alternatively specify the name of the bean using @Resource(name="a")
or @Autowired @Qualifier("A")
at the ifcA
variable. 您也可以在ifcA
变量中使用@Resource(name="a")
或@Autowired @Qualifier("A")
指定Bean的@Resource(name="a")
。 Since you specify the name of the bean here, it is called "autowiring by name". 由于您在此处指定了Bean的名称,因此称为“按名称自动装配”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.