简体   繁体   English

如何从带注释的类spring中引用在spring上下文xml中声明的bean

[英]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.

相关问题 Spring不使用注释在XML上声明的bean自动装配 - Spring not autowiring using annotation a bean declared on the XML 单击spring-context.xml的ref定义时,打开特定的类而不是bean定义 - Open specific class rather than bean definition when clicked ref definition of spring-context.xml 在 spring 框架中创建名称在 class 路径资源 [application-context.xml] 中定义的 bean 时出错 - Error creating bean with name defined in class path resource [application-context.xml] in spring framework 使用xml配置的Spring bean类中的DAO空 - DAO null in spring bean class with xml config Spring:如何将SimpMessagingTemplate bean暴露给root上下文? - Spring : how to expose SimpMessagingTemplate bean to root context ? 基于Spring xml的bean定义,bean元素的类属性 - spring xml based bean definition, class attribute of `bean` element Spring无法从XML读取Bean属性 - Spring unable to read bean property from XML Spring - 从类路径资源[Beans.xml]加载XML bean定义 - NoClassDefFoundError - Spring - Loading XML bean definitions from class path resource [Beans.xml]- NoClassDefFoundError 春季批处理-如何在XML中引用bean属性 - spring batch - how to reference bean properties in XML 如何以编程方式从应用程序上下文创建spring xml配置文件? - How to create spring xml configuration files, from the application context programmaticaly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM