简体   繁体   English

如何使用主要方法访问Spring Boot应用程序中application.properties文件中的值

[英]How to access a value in the application.properties file in Spring Boot app with main method

I have a application.properties in my src/main/resources folder. 我的src / main / resources文件夹中有一个application.properties。 it has one property 它有一个属性

username=myname

I have a class 我有一堂课

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

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

when i call printusername function in my main method as follws 当我在以下主要方法中调用printusername函数时

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

it prints null. 它输出null。 please some one can tell me what i have missed? 请有人可以告诉我我错过了什么?

The @Value annotation, as @Autowired , works only if your class is instantiated by Spring IoC container. @Value注释(如@Autowired )仅在您的类由Spring IoC容器实例化时起作用。

Try to annotate your class with @Component annotation: 尝试使用@Component注释对您的类进行注释:

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

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

Then in your runnable class: 然后在您的可运行类中:

public class RunnableClass {

    private static A object;

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

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

}

This way should work... 这种方式应该起作用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Spring Boot 中访问 application.properties 文件中定义的值 - How to access a value defined in the application.properties file in Spring Boot 在 Spring Boot 中访问 application.properties 文件中定义的值时出现问题 - problem access a value defined in the application.properties file in Spring Boot Spring Boot在application.properties中传递值/ using方法 - Spring Boot passing value / using method inside the application.properties 访问spring启动应用程序.properties中提到的配置文件,在创建.jar后用于App引擎部署 - Access configuration file mentioned in spring boot application.properties after creating the .jar for App engine deployment Spring Boot application.properties 值未填充 - Spring Boot application.properties value not populating 如何在 spring 引导中读取构造函数内的 application.properties 值? - How to read application.properties value inside the constructor in spring boot? 如何从Spring Boot中的application.properties中分配注释值? - How to assign annotation value from application.properties in Spring Boot? Spring boot application.properties 文件读取 - Spring boot application.properties file reading Spring 引导无法识别 application.properties 文件 - Spring Boot not recognizing application.properties file Spring Boot 2:如何使用application.properties文件配置HikariCP - Spring Boot 2: How to configure HikariCP using application.properties file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM