Reputation: 41
I inject a flag using @Value("${FOO}")
and I don't want my spring app start at all if it wasn't provided (i.e., FOO
is a mandatory flag).
Here's my main class:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and I inject FOO
into one of the services.
How can I do it?
Upvotes: 1
Views: 322
Reputation: 162
SpringBoot runners can you used for doing this before the application starts up. you can find examples here https://www.tutorialspoint.com/spring_boot/spring_boot_runners.htm
Upvotes: 0
Reputation: 8491
Resolving of properties placeholders is controlled by PlaceholderConfigurerSupport. And by default it should throw an exception if it was unable to resolve a placeholder:
If a configurer cannot resolve a placeholder, a BeanDefinitionStoreException will be thrown.
However, when I tried to use a @Value
with a property that didn't exist, it threw an exception, but it didn't stop the JVM.
What you can do to force it to stop is to implement InitializingBean
and check the property in the afterPropertiesSet()
method:
@Service
public class YourService implements InitializingBean {
@Value("${foo:#{null}}") // set the default value to null
private String foo;
public void afterPropertiesSet() {
if (foo == null) {
throw new IllegalArgumentException("foo flag must be provided");
}
}
}
Upvotes: 1
Reputation: 952
If you want to inject Foo you need to start your application. This may not be the proper way but this will work. What you can do is to create a bean like this. In the bean you can add your own condition to shutdown the app. This will prevent the start of the app while the bean gets created.
@SpringBootApplication
public class SampleApplication {
@Value("${foo}")
private String foo;
@Bean
public String preventStart() {
if("no".equals(foo) ) {
System.exit(0);
}
return "started";
}
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
Upvotes: 0