【问题标题】:Populate spring bean property using annotations only, at run-time在运行时仅使用注释填充 spring bean 属性
【发布时间】:2019-01-10 19:09:46
【问题描述】:

我有一个只有一个属性 attr 的 bean Parent。

class Parent
{
   String attr;
   public void doStuff(){
      //stuff
   }
   public String getAttr() {
       return attr;
   }
   public void setAttr(String attr) {
       this.attr=attr;
   }
}

我有三个扩展这个父 bean 的 bean。 我的 spring.xml 看起来像这样-

<bean id="parent" class="Parent"/>

<bean id="child1" parent="parent">
    <property name="attr" value="Sample value 1"/>
</bean>

<bean id="child2" parent="parent">
    <property name="attr" value="Sample value 2"/>
</bean>

<bean id="child3" parent="parent">
    <property name="attr" value="Sample value 3"/>
</bean>

我想使用注释做同样的事情。 问题是我必须做这个店面,并且我的控制器中的所有 bean 都被声明为 -

@Resource
@Qualifier("child1")
Parent child1;

有没有一种方法可以使用注释或控制器中的任何其他方法(即不使用 spring.xml)将属性添加到子 bean?

有没有办法使用@Value 注释来做到这一点。问题是我没有来自属性文件的静态值。我对 3 个不同的 bean 有 3 个不同的值。

【问题讨论】:

    标签: java spring properties annotations dependencies


    【解决方案1】:

    如果您的属性文件中有三个不同的值,这不应该工作

    see post here

    @Value(“${child1.attr}”) @Value(“${child2.attr}”) @Value(“${child3.attr}”)

    【讨论】:

    • 这可能吗?我认为这在语法上是不正确的。另外,我没有属性文件。
    • 只要你有来自-properties-file 的属性,@Value 就可以工作
    猜你喜欢
    • 2015-12-14
    • 2023-03-16
    • 1970-01-01
    • 2010-09-23
    • 2012-08-06
    • 2018-10-24
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多