I’m just setting up a web application using Spring 3.1 and I’m trying to do this by using java configuration.
I have two configuration classes “AppConfig” (general bean definitions) and “WebConfig” (Spring MVC configuration). How can I reference a bean that has been declared in AppConfig in the WebConfig class?
Below, the validator in the AppConfig configuration class should use the messageSource fromn WebConfig.
AppConfig:
@Configuration
@ComponentScan(basePackages = { "com.example" })
public class AppConfig {
@Bean
public Validator validator() {
final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
}
WebConfig:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.example.common.web", "com.example.web" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
return messageSource;
}
}
When I want to reference a bean from the same configuration class, I’d just call its setup method, but I obviously cannot do this when the bean is declared in another class.
Your advice will be greatly appreciated!
There are two ways to do so:
or, as Aaron Digulla mentioned:
I prefer the first form, with one autowiring you can access the whole configuration, and then you can access its beans, by calling
theNewBean.setValidator(appConfig.validator());.