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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With