【问题标题】:How to get values from Application.properties or yaml file in a non Spring class如何从非 Spring 类中的 Application.properties 或 yaml 文件中获取值
【发布时间】:2021-08-02 03:04:28
【问题描述】:

我有一个 Spring 应用程序,我正在使用 new 运算符为一个类创建一个对象。在课堂上,我试图从我的application.properties 中获取值。我用 @Service 注释了这个类,我正在用 new 运算符创建一个对象。没什么区别。

@Service
public class Myclass {
    @Value("$(myVariable)")
    private String myvariable;
}

我在其中使用 new 运算符创建上述类的对象的类

public class AnotherNonSpringClass {
    MyClass myclass = new MyClass();
}

如何从application.properties 获取值?

【问题讨论】:

标签: java spring


【解决方案1】:

当您使用 new 关键字创建对象时,您必须管理对象 spring 不会维护由 new 关键字创建的对象

但仍然有机会通过使用 new 关键字创建对象来注入属性,只是您需要为您提供属性值的服务。

public class ValueProvider {
    public String getProperty(String propertyName) throws IOException {
        Properties prop = new Properties();
        prop.load(new FileInputStream(ResourceUtils.getFile("classpath:application.properties")));
        return prop.getProperty(propertyName);
    }
}

之后

public class AnotherNonSpringClass {
   MyClass myClass = new MyClass(new ValueProvider().getProperty("myvariable"));
}

最后,

@Service
public class MyClass
{
    @Value("$(myVariable)")
    private String myvariable;

    public MyClass() {}

    public MyClass(String prop) { 
        this.myVariable = prop; 
    }
}

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 2018-01-07
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2021-04-16
    • 1970-01-01
    • 2016-04-04
    相关资源
    最近更新 更多