开发自己的Convert,用在application.yml解析中

先直接呈现各种调试后的代码吧

application.yml

1
2
3
4

tmp2:
  weight: 10kg

Weight.java

1
2
3
4
5
6
7
8

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Weight {
    private Long weight;
}

WeightConvert.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

public class WeightConverter implements Converter<String, Weight> {
    @Override
    public Weight convert(String source) {
        if (source.endsWith("kg")) {
            return new Weight(Long.valueOf(source.substring(0, source.length() - 2)));
        }
        return null;
    }
}

TmpConfiguration.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

@Configuration
public class TmpConfiguration {
    @Bean
    @ConfigurationPropertiesBinding
    public WeightConverter weightConverter() {
        return new WeightConverter();
    }
}

Tmp2Properties.java

1
2
3
4
5
6
7
8

@Data
@Component
@ConfigurationProperties(prefix = "tmp2")
public class Tmp2Properties {
    private Weight weight;
}

实验总结

本次实验中最核心的一点是要将WeightConverter注入到Spring Context中,并让Spring Context知道这个类是用来做转换的。实验中采用了如下的代码实现:

1
2
3
4
5
6
7

@Bean
@ConfigurationPropertiesBinding
public WeightConverter weightConverter() {
    return new WeightConverter();
}

其中@ConfigurationPropertiesBinding注解就是让Spring Boot知道使用该住户按期做数据绑定。在理解这个实验核心的部分后,我们可以使用如下的方式开发Converter,并移除TmpConfiguration.java。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13

@Component
@ConfigurationPropertiesBinding
public class WeightConverter implements Converter<String, Weight> {
    @Override
    public Weight convert(String source) {
        if (source.endsWith("kg")) {
            return new Weight(Long.valueOf(source.substring(0, source.length() - 2)));
        }
        return null;
    }
}

参考资料

  1. @ConfigurationProperties 注解使用姿势,这一篇就够了