从外部类调用时,解析@Value失败 - spring java

时间:2017-03-03 13:42:03

标签: java spring

在属性文件(config.properties)中,我定义了几个属性:

my.property.first=xyz
my.property.second=12

我创建了一个类来读取这些属性:

package my.package.first;
............

@Configuration
public Class MyProperties {

    @Value("${my.property.first}") private String propertyFirst;

    @Value ("${my.property.second}") private String propertySecond;

    public String getPropertyFirst() {
        return propertyFirst;
    }

    public int getPropertySecond() {
        return propertySecond
    }

    @Bean 
    public MyProperties getInstance() {
        return this;
    } 
}

现在我想在放在其他包中的类中使用这些属性:

package my.otherpackage.third;

import my.property.package.first.MyProperties;
.............................
public class GetMyProperties{

    AnnotationConfigApplicationContext context  = new AnnotationConfigApplicationContext(MyProperties.class);

    MyProperties myProperties =context.getBean("getInstance",MyProperties.class);

    //This returns ${my.property.first}
    String propertyFirst = myProperties.getPropertyFirst();

    // This returns ${my.property.second}
    int propertySecond = context.getBeanFactory().resolveEmbeddedValue(("${my.property.first}"));
}

我尝试仅使用Annotations来解决这个问题。

我使用的是Spring 4.

谢谢

1 个答案:

答案 0 :(得分:0)

MyProperties不是真正的@Configuration类,它是一个bean。给它注释@Component并将@Bean声明移动到另一个@Configuration类。为spring定义bean的位置无关紧要(只要它在配置类中),如果你的应用程序中有@ComponentScan或@SpringBootApplication,它会把它拿起来,我很确定你做。您创建@Component

的MyProperties类

你想要:

@Component
public class MyProperties {
    @Value("${my.property.first}") private String propertyFirst;

    @Value ("${my.property.second}") private String propertySecond;

    public String getPropertyFirst() {
        return propertyFirst;
    }

    public void setPropertyFirst(String propertyFirst){
        this.propertyFirst = propertyFirst;
    }

    public int getPropertySecond() {
        return propertySecond
    }

    public void setPropertySecond(String propertySecond){
        this.propertySecond= propertySecond;
    }
}



@Configuration
public class Config {
    @Bean 
    public MyProperties getInstance() {
        return new MyProperties();
    } 
}



package my.otherpackage.third;

import my.property.package.first.MyProperties;
.....
@EnableAutoConfiguration
@ComponentScan(basePackages = {"my"})
public class GetMyProperties{
    public static void main(String[] args){
        AnnotationConfigApplicationContext context  = new AnnotationConfigApplicationContext(GetMyProperties.class);

        MyProperties myProperties =context.getBean("getInstance",MyProperties.class);

        //This returns the value of ${my.property.first}
        String propertyFirst = myProperties.getPropertyFirst();

        // This returns the value of ${my.property.second}
        int propertySecond = myProperties.getPropertySecond();
    }
}