【问题标题】:Spring 3.1: How do I inject a bean created in a different configuration classSpring 3.1:如何注入在不同配置类中创建的 bean
【发布时间】:2012-09-13 08:13:44
【问题描述】:

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

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

应用配置:

@Configuration
@ComponentScan(basePackages = { "com.example" })
public class AppConfig {

    @Bean
    public Validator validator() {
        final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

}

网络配置:

@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 在另一个类中声明时我显然不能这样做。

您的建议将不胜感激!

【问题讨论】:

    标签: java spring


    【解决方案1】:

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

    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Autowired
        private Validator validator;
    
        ...
    }
    

    【讨论】:

    • 起来,我闭嘴!谢谢! :-)
    • +1 他还可以在方法级别自动装配validator,作为参数传递给方法validator(ReloadableResourceBundleMessageSource messageSource)。他想在AppConfig中自动连接ReloadableResourceBundleMessageSource messageSource
    【解决方案2】:

    有两种方法:

    public class WebConfig {
        @Autowired
        AppConfig appconfig;
    
        ...
    }
    

    或者,正如 Aaron Digulla 所说:

    public class WebConfig {
        @Autowired
        Validator validator;
    
        ...
    }
    

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

    【讨论】:

    • 第一种形式不允许您覆盖 bean 进行测试。
    • 谢谢!我接受了这个答案,因为它提供了更多信息。
    【解决方案3】:

    我认为 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      相关资源
      最近更新 更多