9
votes

I'm using @ConfigurationProperties to configure the delay of a background task in Spring boot and I'm trying to use this value from a @Scheduled annotation on another component. However, in order to make it work I must use the full name given to the bean by Spring.

The configuration properties class is as follows:

@ConfigurationProperties("some")
class SomeProperties {
    private int millis; //the property is some.millis

    public int getMillis() {
        return millis;
    }

    public void setMillis(int millis) {
         this.millis = millis;
    }
}

And I'm using the value as follows in the scheduled method:

@Component
class BackgroundTasks {

    @Scheduled(fixedDelayString = "#{@'some-com.example.demo.SomeProperties'.millis}") //this works.
    public void sayHello(){
        System.out.println("hello");
    }
}

Is it possible to reference the value without having to use the full name of the bean? This answer suggests it is possible but I haven't been able to make it work.

2

2 Answers

10
votes

Using @Componenton the properties class allows to access the property as "#{@someProperties.persistence.delay}.

More info in the spring boot documentation.

0
votes

Following should work fine assuming bean is created with someProperties by default and name is not overridden.

@Scheduled(fixedDelayString = "#{@someProperties.getMillis()}")