One configuration class may need to reference a bean defined in
another configuration class (or in XML, for that matter). The preferred
mechanism for doing this is using Spring's @Autowired
annotation:
One @Configuration
class may directly reference bean instances registered
from another using Spring's @Autowired
annotation.
@Configuration public class ConfigOne { @Bean public AccountRepository accountRepository() { // create and return an AccountRepository object } } @Configuration @AnnotationDrivenConfig public class ConfigTwo { @Autowired AccountRepository accountRepository; @Bean public TransferService transferService() { return new TransferServiceImpl(accountRepository); } }
Given that both these configuration classes are supplied to the
application context at runtime, the AccountRepository
bean
declared in ConfigOne
will be autowired (injected) into the
AccountRepository
field in ConfigTwo
.
JavaConfigApplicationContext context = new JavaConfigApplicationContext(ConfigOne.class, ConfigTwo.class);
In addition to being able to reference any particular bean definition as
seen above, one @Configuration
class may reference the instance
of any other @Configuration
class using @Autowired
. This works
because the @Configuration
classes themselves are instantiated and managed
as individual Spring beans.
@Configuration public class ConfigOne { @Bean public AccountRepository accountRepository() { // create and return an AccountRepository object } } @Configuration @AnnotationDrivenConfig public class ConfigTwo { @Autowired ConfigOne configOne; @Bean public TransferService transferService() { // transferService references accountRepository in a 'fully-qualified' fashion: return new TransferServiceImpl(configOne.accountRepository()); } }
Tip | |
---|---|
The 'fully-qualified' approach is generally preferred as it provides a the significant advantage of being able to easily navigate within an IDE to the source of the referenced bean. |
Open issue: Should @AnnotationDrivenConfig
be enabled by default?
Rationale: given that @Autowired
is the preferred method for
referencing external beans, it is likely to need to be enabled in all but the
most trivial configurations. See
SJC-219.