在不使用 XML 的 ref 标记的情况下引用另一个 Bean



我需要在Spring中从另一个bean访问一个bean。对此,我所知道的最明显的解决方案是在spring配置文件中使用ref标签。但是,假设我无法修改spring配置文件。是否有其他方法访问其他bean中的bean ?

几个选项:

  • 使用注释- @Inject private AnotherBean bean;(或@Autowired)(首选)
  • 获取ApplicationContext(例如实现ApplicationContextAware),调用.getBean(..)

Java:

class MyBean {
    @Autowired
    private OtherBean theBeanYouWantToGet;
}
XML:

<beans ...>
    <context:annotation-config/>
    <import resource="the-other-xml-file-that-you-can't-touch.xml"/>
    <bean class="...MyBean"/>
</beans>

最新更新