简体   繁体   中英

How to refer a bean declared in spring context xml from an annotated class spring

Example:

spring context xml

<beans>
<bean id="a" class="ClassA" />
</beans>

@Service public class Test {

@Resource InterfaceA ifcA;

}

public class ClassA implements InterfaceA { }

public interface InterfaceA { }


I would like to know how I can refer to xml bean declared in xml from a java class that has annotations enabled.

One way I know would be get the context and then get the bean.

Please suggest.

In your annotated class, declare this

@Autowired InterfaceA ifcA;

Spring will automatically populate with the appropriate bean instance.

Your code should work out of the box since Spring takes care of @Resource annotations as well. It looks up the corresponding bean by the requested type (that's why it's called "autowiring by type").

You may alternatively specify the name of the bean using @Resource(name="a") or @Autowired @Qualifier("A") at the ifcA variable. Since you specify the name of the bean here, it is called "autowiring by name".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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