I have a Spring Boot 2.7 Web/MVC server application with profiles for different environments (DEV/QA/PROD). I have a common application.properties
with shared configuration and environment specific configuration, for example, JDBC URLs in separate application-<environment>.properties
on the classpath.
If the application is started without a profile being selected, it fails with a cryptic error message complaining about a jdbcUrl
property missing and not being able to initialize the context - all this within a huge stack trace. This is self-explanatory for the developer, but not trivial for an operations person.
What would be the Spring way of checking if exactly one profile is selected and displaying a non-stacktrace, human (operator) friendly error message? I am looking for something similar to what is shown if the server port is already in use. I would like to avoid hacks and find the Spring-endorsed solution for this.
CodePudding user response:
it fails with a cryptic error message complaining about a
jdbcUrl
property missing and not being able to initialize the context - all this within a huge stack trace
The more fundamental problem seems to be that you're fighting the built-in Boot facilities that provide assistance to humans out of the box. Instead of using @Value("${jdbcUrl}")
in your code, you should inject a javax.sql.DataSource
, and Boot will automatically configure one when spring.datasource.url
is set. If it's not present, you'll get an error that says "no bean of DataSource is available", and the auto-config report will explain why.
CodePudding user response:
You can use a postprocessor for a value . If it is not present, then log your human friendly error error message and quit the application.
e.g
@Bean
public BeanPostProcessor bpp(Environment environment) {
return new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(environment.getActiveProfiles()[0].equalsIgnoreCase(environment.getDefaultProfiles()[0])){
// Your Error message goes here
System.exit(1);
}
return bean;
}
};
}