13.07.2015 Views

Spring JavaConfig Reference Guide - Spring Web Services - Parent ...

Spring JavaConfig Reference Guide - Spring Web Services - Parent ...

Spring JavaConfig Reference Guide - Spring Web Services - Parent ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Modularizing configurations5.2. Referencing externally defined beans with @ExternalBeanOne configuration class may need to reference a bean defined in another configuration class (or in XML, forthat matter). The @ExternalBean annotation provides just such a mechanism. When <strong>JavaConfig</strong> encounters amethod annotated as @ExternalBean, it replaces that method definition with a lookup to the enclosing beanfactory for a bean with the same name as the method name.@Configurationpublic class ConfigOne {@Beanpublic AccountRepository accountRepository() {// create and return an AccountRepository object}}@Configurationpublic abstract class ConfigTwo {@Beanpublic TransferService transferService() {return new TransferServiceImpl(accountRepository());}}@ExternalBeanpublic abstract AccountRepository accountRepository();Given that both these configuration classes are supplied to the application context at runtime, <strong>JavaConfig</strong> willbe able to resolve the 'accountRepository' @ExternalBean by name and everything will 'wire-up' accordingly.<strong>JavaConfig</strong>ApplicationContext context = new <strong>JavaConfig</strong>ApplicationContext(ConfigOne.class, ConfigTwo.class);5.3. Importing @Configuration classes with @Import@Import represents <strong>JavaConfig</strong>'s equivalent of XML configuration's element. One configurationclass can import any number of other configuration classes, and their bean definitions will be processed as iflocally defined.@Configurationpublic class DataSourceConfig {@Beanpublic DataSource dataSource() {return new DriverManagerDataSource(...);}}@Configuration@Import(DataSourceConfig.class)public class AppConfig extends ConfigurationSupport {@Beanpublic void TransferService transferService() {return new TransferServiceImpl(getBean(DataSource.class);}}Importing multiple configurations can be done by supplying an array of classes to the @Import annotation@Configuration@Import({ DataSourceConfig.class, TransactionConfig.class })public class AppConfig extends ConfigurationSupport {// bean definitions here can reference bean definitions in DataSourceConfig or TransactionConfig}<strong>Spring</strong> <strong>JavaConfig</strong> 19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!