In my current application I am having a properties file which has certain properties of student and I am writing a class with a main function to extract those properties and Iam using below code, but I am getting null values for all properties,I tried using getproperty() and it is working fine but I need to do this using @Value . Any solution?
@Configuration
@PropertySource("classpath:sample.properties")
public class Test
{
@Value("${student.name}")
private String name;
public void test()
{
System.out.println("name " name);
}
public static void main(String args[])
{
Test t=new Test();
t.test();
}
I'm getting
name = null
CodePudding user response:
your test class,
@Configuration
public class Tester {
@Value("${student.name}")
private String name;
public String getName(){
return name;
}
}
You should use application context provided by spring boot like this,
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(DemoApplication.class);
ApplicationContext context = application.run(args);
// you can get object of any class like this.
Test testObj = context.getBean(Test.class);
System.out.println("Student Name : " testObj.getName());
}
}
Hope it helps.