How to access value in application.properties file in Spring boot application with main method

I have application.properties in my src / main / resources folder. 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 the printusername function in my main method as described below

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

it prints zero. please can anyone tell me what i missed?

+4
source share
1 answer

Annotation @Value, like @Autowired, only works if your class is instantiated by the Spring IoC container.

Try annotating your class with 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();
    }

}

...

+5

Source: https://habr.com/ru/post/1679216/


All Articles