Spring 3.1:如何注入在不同配置类中创建的bean

时间:2012-09-13 08:13:44

标签: java spring

我只是使用Spring 3.1设置一个Web应用程序,我试图通过使用java配置来实现这一点。 我有两个配置类“AppConfig”(通用bean定义)和“WebConfig”(Spring MVC配置)。如何引用已在WebConfig类中的AppConfig中声明的bean?

下面,AppConfig配置类中的验证器应该使用来自WebConfig的messageSource。

的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;
    }

}

当我想从同一个配置类引用一个bean时,我只是调用它的setup方法,但是当bean在另一个类中声明时,我显然不能这样做。

非常感谢您的建议!

3 个答案:

答案 0 :(得分:6)

配置也是bean,因此您可以使用@Autowired

public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Validator validator;

    ...
}

答案 1 :(得分:4)

有两种方法:

public class WebConfig {
    @Autowired
    AppConfig appconfig;

    ...
}

或者,正如Aaron Digulla所说:

public class WebConfig {
    @Autowired
    Validator validator;

    ...
}

我更喜欢第一种形式,只需一次自动装配即可访问整个配置,然后通过调用theNewBean.setValidator(appConfig.validator());来访问其bean。

答案 2 :(得分:2)

我认为Aaron Digulla和Amir Pashazadeh都是正确的,但自从JSR 330推出以来,还有另一个注释。您也可以使用@Inject

@Inject
private Validator validator;

http://docs.spring.io/spring/docs/3.0.x/reference/beans.html#beans-autowired-annotation