Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring autowire only if bean is present as method argument

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(...);
}
like image 568
alturkovic Avatar asked Oct 18 '22 18:10

alturkovic


1 Answers

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);
}
like image 68
Olivier Boissé Avatar answered Oct 21 '22 08:10

Olivier Boissé