1

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?

JWC
  • 1,745
  • 2
  • 12
  • 14
  • You mean access it programatically? Can you post some more details about your problem? – Ryan Gross Jul 15 '11 at 19:08
  • Please look at this answer http://stackoverflow.com/questions/812415/why-is-springs-applicationcontext-getbean-considered-bad – zacheusz Jul 15 '11 at 19:15
  • Yes programmatically or via annotations. But I'm trying to avoid modifying the XML to access the other beans. – JWC Jul 15 '11 at 19:22

2 Answers2

3

A few options:

  • use annotations - @Inject private AnotherBean bean; (or @Autowired) (preferred)
  • get ahold of the ApplicationContext (for ex. implement ApplicationContextAware) and call .getBean(..)
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

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>
Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199