JWC
JWC

Reputation: 1745

Referencing another bean without using XML's ref tag

I need to access a bean from another bean in Spring. The obvious solution to this, that I know of, is to use the ref tag in the spring config file. But let's say I am not able to modify the spring config file. Is there another way to access beans within other beans?

Upvotes: 1

Views: 288

Answers (2)

Bozho
Bozho

Reputation: 597016

A few options:

  • use annotations - @Inject private AnotherBean bean; (or @Autowired) (preferred)
  • get ahold of the ApplicationContext (for ex. implement ApplicationContextAware) and call .getBean(..)

Upvotes: 3

Ryan Stewart
Ryan Stewart

Reputation: 128759

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>

Upvotes: 2

Related Questions