java - 如何使用注释在 @Scope ("prototype") bean 中指定实例特定的 @Value?

标签 java spring spring-annotations

我有一个包含同一组件的两个 Autowiring 实例的 bean:

@Component
public SomeBean {
    @Autowired
    private SomeOtherBean someOtherBean1;
    @Autowired
    private SomeOtherBean someOtherBean2;
    ...
}

SomeOtherBean 有一个原型(prototype)作用域:

@Component
@Scope("prototype")
public SomeOtherBean {
    @Value("...")
    private String configurable;
}

每个 Autowiring 的 SomeOtherBean 的可配置值需要不同,并将通过属性占位符提供:

configurable.1=foo
configurable.2=bar

理想情况下,我想使用注释来指定可配置属性的值。

通过 XML 执行此操作很容易,但我想知道这是否是

  • a) 无法使用注释或
  • b) 如何做到。

最佳答案

也许这与您的想法略有不同,但您可以使用基于 @Configuration 的方法轻松完成,例如:

@Configuration
public class Config {

    @Bean
    @Scope("prototype")
    public SomeOtherBean someOtherBean1(@Value("${configurable.1}") String value) {
        SomeOtherBean bean = new SomeOtherBean();
        bean.setConfigurable(value);
        return bean;
    }

    @Bean
    @Scope("prototype")
    public SomeOtherBean someOtherBean2(@Value("${configurable.2}") String value) {
        // etc...
    }
}

关于java - 如何使用注释在 @Scope ("prototype") bean 中指定实例特定的 @Value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19004489/

相关文章:

java - Spring 和 Quartz 与 Java Config 的集成

java - CDI 不能注入(inject) pojo java 类。 (带有限定符@Default 的 Pojo 类型的依赖关系不满足)

java - InternalResourceViewResolver 未解析

android - 无法执行dex : Multiple dex files define Lorg/springframework/http/HttpEntity

java - Spring 测试 : How to default configuration to @AnnotationDriven?

caching - 过度类型匹配的结果 - 考虑使用 'getBeanNamesOfType' 并关闭 'allowEagerInit' 标志

java - JUnit 中的断言解决方法

java - 将一种方法从一个类实现到另一个类?

java - 通过使用 Java 8 将元素添加到链表中来比较数组列表和链表

java - 使用@ComponentScan元注释的Spring自定义@Enable批注