Reputation: 27068
I am trying my hands on Micronaut. One of the things I noticed is that Micronaut doesn't failfast.
For example If I have something like this in my bean
@Value("${my.url}")
private String url;
And if there is no property defined with key my.url, then
I would assume it would be better to failfast(as in springboot). So was wondering if this is possible in micronaut as well.
Upvotes: 4
Views: 1469
Reputation: 481
Use eager initialization to make the application fail at startup if there are configuration errors. Example from the Micronaut docs, for cases where the configuration properties are in dedicated beans annotated with @ConfigurationProperties
or similar:
public class Application {
public static void main(String[] args) {
Micronaut.build(args)
.eagerInitConfiguration(true) // Add this to fail fast
.mainClass(Application.class)
.start();
}
}
However, this won't work for configuration properties in regular beans. You can move the configuration to dedicated configuration beans, or, if that'd be too messy, you can tell Micronaut to eagerly initialize everything, which will increase startup time but will fail fast if beans can't be initialized. Replace eagerInitConfiguration
with eagerInitSingletons
in the above example (and see the docs for more details).
Upvotes: 3
Reputation: 7985
You can use @ConfigurationProperties
for this and make sure it is @Context
scope since by default Micronaut beans are not created on startup. By making them @Context
scope the bean will be created when the application starts.
The following:
import io.micronaut.context.annotation.*;
import javax.validation.constraints.*;
@ConfigurationProperties("my")
@Context
class MyConfig {
private @NotNull String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Results in
08:38:38.568 [main] ERROR io.micronaut.runtime.Micronaut - Error starting Micronaut server: Bean definition [fresh.java.MyConfig] could not be loaded: Error instantiating bean of type [fresh.java.MyConfig]
Message: Validation failed for bean definition [fresh.java.MyConfig]
List of constraint violations:[
url - must not be null
]
When the server startups up.
Make Sure you add this dependency
compile "io.micronaut.configuration:micronaut-hibernate-validator"
Upvotes: 6