Java – spring 3.1: how to inject beans created in different configuration classes
•
Java
I just set up a web application using spring 3.1, and I try to do this by using java configuration
Next, the verifier in the AppConfig configuration class should use the MessageSource from 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 just call its setup method, but when the bean is declared in another class, I obviously can't do so
Thank you very much for your advice!
Solution
There are two ways to do this:
public class WebConfig {
@Autowired
AppConfig appconfig;
...
}
Or, as Aaron digulla said:
public class WebConfig {
@Autowired
Validator validator;
...
}
I prefer the first form. One is automatic assembly. You can access the whole configuration, and then you can call newbean setValidator(appConfig.validator()); To access its bean
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
