Yasitha Bandara
Yasitha Bandara

Reputation: 351

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?

Upvotes: 4

Views: 6281

Answers (1)

davioooh
davioooh

Reputation: 24706

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

Upvotes: 5

Related Questions