Search code examples
javaspringspring-bootproperties-file

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?


Solution

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