Home > database >  How accept both long and double in Spring @ConfigurationProperties annotation?
How accept both long and double in Spring @ConfigurationProperties annotation?

Time:01-07

Here is my yaml file:

collie:
    crontask:
        command: echo ok
        intervalInMinute: 0.5

Here is the code:

@Configuration
@ConfigurationProperties(prefix = "collie.crontask")
@Data
public class CronTaskConfig {

    private String command;

    private Long intervalInMinute;

    public void setIntervalInMinute(String intervalInMinute) {
        this.intervalInMinute = Long.parseLong(intervalInMinute);
    }
}

But I got this error:

Failed to bind properties under 'collie.crontask' to com.xx.union.collie.worker.config.CronTaskConfig$$EnhancerBySpringCGLIB$$e4948fd7:

    Property: collie.crontask.intervalinminute
    Value: 0.5
    Origin: class path resource [application.yaml]:45:23
    Reason: For input string: "0.5"

Action:

Update your application's configuration`
and :
 org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'cronTaskConfig': Could not bind properties to 'CronTaskConfig'

But when I set intervalInMinute: 1, it works.

It looks like the problem is the type of value.

Can anyone help me to solve this problem?

CodePudding user response:

0.5 is not a Long, and can't be converted. Changing to a double should work.

CodePudding user response:

The value 0.5 is an invalid long value. You could parse the double value first:

public void setIntervalInMinute(String intervalInMinute) {
    this.intervalInMinute = (long) Double.parseDouble(intervalInMinute);
}
  • Related