Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

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

it prints null. please some one can tell me what i have missed?

like image 595
Yasitha Bandara Avatar asked Jun 14 '17 07:06

Yasitha Bandara


1 Answers

The @Value annotation, as @Autowired, works only if your class is instantiated by Spring IoC container.

Try to annotate your class with @Component annotation:

@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...

like image 59
davioooh Avatar answered Nov 03 '22 23:11

davioooh