I am using @ConditionalOnProperty
to create a FileCompressor
bean:
@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", matchIfMissing = true)
public FileCompressor fileCompressor() {
return new DefaultFileCompressor(...);
}
I would like to autowire FileCompressor
bean only if it is present, null
if file.rollover.sink.compress=false
as a method argument.
But if I try to define it like:
@Bean
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator, final @Autowired(required = false) FileCompressor fileCompressor) {
return new RolloverTask(intervalCalculator, fileCompressor);
}
I am getting the following error:
Parameter 1 of method rolloverTask in com.example.FileRolloverSinkConfiguration required a bean of type 'com.example.compressor.FileCompressor' that could not be found.
- Bean method 'fileCompressor' in 'FileRolloverSinkConfiguration' not loaded because @ConditionalOnProperty (file.rollover.sink.compress) found different value in property 'compress'
What changes should I make to autowire or pass null
if not present?
-- EDIT --
My solution:
private FileCompressor fileCompressor;
@Autowired(required = false)
public void setFileCompressor(final FileCompressor fileCompressor) {
this.fileCompressor = fileCompressor;
}
@Bean
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator) {
log.info("Creating a new rollover task with{} a file compressor", fileCompressor == null ? "out" : "");
return new RolloverTask(intervalCalculator, fileCompressor);
}
@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", matchIfMissing = true)
public FileCompressor fileCompressor() {
return new DefaultFileCompressor(...);
}
I think you can use the annotations @ConditionalOnBean
and @ConditionalOnMissingBean
I didn't try the code but it should be like this :
@Bean
@ConditionalOnBean(FileCompressor.class)
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator, final FileCompressor fileCompressor) {
return new RolloverTask(intervalCalculator, fileCompressor);
}
and
@Bean
@ConditionalOnMissingBean(FileCompressor.class)
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator) {
return new RolloverTask(intervalCalculator, null);
}
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