【问题标题】:How to access a value in the application.properties file in Spring Boot app with main method如何使用 main 方法在 Spring Boot 应用程序中访问 application.properties 文件中的值
【发布时间】:2017-11-16 04:29:05
【问题描述】:

我的 src/main/resources 文件夹中有一个 application.properties。 它有一个属性

username=myname

我有课

public class A
{
    @Value("${username}")
    private String username;

    public void printUsername()
    {
       System.out.println(username);
    }
}

当我在我的主要方法中调用 printusername 函数时

public static void main(String[] args) 
{
    A object=new A();
    object.printUsername();
}

它打印空。 请有人能告诉我我错过了什么?

【问题讨论】:

  • username 变量和printUsername() 方法标记为static 并尝试。
  • 我试过了。但没用

标签: java spring spring-boot properties-file


【解决方案1】:

@Value 注释,如 @Autowired,仅当您的类由 Spring IoC 容器实例化时才有效。

尝试使用@Component 注释来注释您的类:

@Component
public class A
{
    @Value("${username}")
    private String username;

    public void printUsername()
    {
       System.out.println(username);
    }
}

然后在你的可运行类中:

public class RunnableClass {

    private static A object;

    @Autowired
    public void setA(A object){
        RunnableClass.object = object;
    }

    public static void main(String[] args) 
    {
        object.printUsername();
    }

}

这种方式应该可行...

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2015-08-12
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2021-03-19
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多