Reputation: 2292
@SpringBootApplication
public class App {
@Value("${Application}")
private String application;
@Value("${APP_SERVER_CPU_ENABLED}")
private String APP_SERVER_CPU_ENABLED;
@Value("${APP_SERVER_MEMORY_ENABLED}")
private String APP_SERVER_MEMORY_ENABLED;
@Autowired
MonitoringItems mI;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
MonitoringItems mI=null;
try {
System.out.println(APP_SERVER_CPU_ENABLED);
System.out.println(APP_SERVER_MEMORY_ENABLED);
if (APP_SERVER_MEMORY_ENABLED.equalsIgnoreCase("true") && APP_SERVER_CPU_ENABLED.equalsIgnoreCase("true")) {
//do something
}
How come the main class cannot read the @Value annotations? In my other classes I have to put @Configuration, @ComponentScan, @EnableAutoConfiguration above the class and then @PostConstruct above the constructor. And I was able to retrieve the values from the application.properties. How would I be able to do that for the main class?
Upvotes: 0
Views: 6668
Reputation: 126
So after 3 years i show you an astuce to do that.
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Demo1Application .class, args);
Test test = context.getBean(Test.class);
String password = test.getPassword();
System.out.println(password);
}
@Component
class Test {
@Value("${password}")
private String password;
public String getPassword() {
return password;
}
}
}
of course you create your property in a file properties like application.properties for example :
password = sxqdqdqdqdqdqd
Upvotes: 2
Reputation: 2950
The problem is that you cannot make your @Value
s static, because Spring may not have initialized them yet. You can however get the value you want BEFORE spring is initialized by retrieving them from the system/environment variables instead of via a properties file.
String value = System.getProperty("SOME_KEY");
Upvotes: 1