When use spring annotation @Bean
to declare some instances, the arguments be injection, and these are required, if can't find instance, will throw NoSuchBeanException.
How to make it optional? Something like @Autowired(required = false)
For example
@Configuration
class SomeConfiguration {
@Bean
public SomeComponent someComponent(Depend1 depend1,
Depend2 depend2) {
SomeComponent someComponent = new SomeComponent();
someComponent.setDepend1(depend1);
if (depend2 != null) {
someComponent.setDepend2(depend2);
}
return someComponent;
}
}
Optional dependencies are used when it's not possible (for whatever reason) to split a project into sub-modules. The idea is that some of the dependencies are only used for certain features in the project and will not be needed if that feature isn't used.
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.
You can use @Autowired(required = false)
on a parameter:
@Configuration
class SomeConfiguration {
@Bean
public SomeComponent someComponent(Depend1 depend1,
@Autowired(required = false) Depend2 depend2) {
SomeComponent someComponent = new SomeComponent();
someComponent.setDepend1(depend1);
if (depend2 != null) {
someComponent.setDepend2(depend2);
}
return someComponent;
}
}
Just use Optional
:
@Bean
public SomeComponent someComponent(Depend1 depend1, Optional<Depend2> depend2) {
...
}
Or you could define multiple profiles like so
@Configuration
@Profile("dev")
class DevConfiguration {
@Bean
public SomeComponent someComponent(Depend1 depend1) {
SomeComponent someComponent = new SomeComponent();
someComponent.setDepend1(depend1);
return someComponent;
}
}
and
@Configuration
@Profile("prod")
class ProdConfiguration {
@Bean
public SomeComponent someComponent(Depend1 depend1, Depend2 depend2) {
SomeComponent someComponent = new SomeComponent();
someComponent.setDepend1(depend1);
someComponent.setDepend2(depend2);
return someComponent;
}
}
when you now start your application with the command line argument -Dspring.profiles.active="dev"
or -Dspring.profiles.active="prod"
it'll select the correct bean for you. In case multiple profiles,test and dev for example, require the same implementation you can simply replace @Profile("dev")
with @Profile({"dev","test"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With