Reputation: 2810
I have a very simple Spring application, but I can't not get a System.out.println
statement to print into the console.
This is the main app file where I am printing an env variable set in a .yml
file
import path.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainApplication {
@Autowired
private Config config;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MainApplication.class);
app.run();
}
public void run(String... args) throws Exception {
System.out.println("env: " + config.getEnv());
}
}
The configuration file looks like this:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class Config {
private String env;
public void setEnv(String env) {
this.env = env;
}
public String getEnv() {
return this.env;
}
}
Finally the properties yml file
spring:
profiles.active: dev
h2:
console:
enabled: true
---
spring:
profiles: dev
env: dev
---
spring:
profiles: test
env: test
---
spring:
profiles: prod
env: prod
The Spring app builds a runs fine, however, I can't see the env
variable to show in the terminal. I have seen examples of people using Controllers with a Request endpoint just to debug the environment variables in the browser. Is that the only option?
Upvotes: 0
Views: 306
Reputation: 40078
Couple of changes to your code, you don't need to use new
keyword for starting spring application, you can directly use static run method
public static void main(String[] args) {
SpringApplication.run(MainApplication.class);
}
Second thing the run
method in MainApplication
will only execute if that class implements CommandLineRunner
@SpringBootApplication
public class MainApplication implements CommandLineRunner {
@Autowired
private Config config;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class);
}
public void run(String... args) throws Exception {
System.out.println("env: " + config.getEnv());
}
}
Upvotes: 2