pf4j spring 插件配置处理
pf4j spring 提供的spring 能力有点弱,但是我们可以自己扩展实现spring 插件类似spring boot 的配置处理能力
问题
比如我们需要实现如下的配置,自定转换,但是因为默认的spring 项目是不直接支持此特性的
@Configuration
@PropertySource(name ="dalongdemo",value = "classpath:app.yaml")
public class MyConfigProperties {
private String name;
private int age;
private String demoname;
public String getDemoname() {
return demoname;
}
public void setDemoname(String demoname) {
this.demoname = demoname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "MyConfigProperties{" +
"name='" + name + '\'' +
", age=" + age +
", demoname='" + demoname + '\'' +
'}';
}
}
解决方法
可以在spring 插件的 createApplicationContext 中进行ConfigurationPropertiesBindingPostProcessor 注册,这样我们就能使用此功能了
参考
applicationContext.register(PluginCConfig.class,MyConfigProperties.class, ConfigurationPropertiesBindingPostProcessor.class);
yaml 格式prefix 问题
此问题就需要强制指定下
@EnableConfigurationProperties(MyConfigProperties.class)
同时还需要自定义一个prefix 处理的,比如基于yaml 的
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
property 类
@ConfigurationProperties(prefix = "demoapp")
@Configuration
@PropertySource(name ="dalongdemo",value = "classpath:app.yaml",factory = YamlPropertySourceFactory.class)
public class MyConfigProperties {
private String name;
private int age;
private String demoname;
public String getDemoname() {
return demoname;
}
public void setDemoname(String demoname) {
this.demoname = demoname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "MyConfigProperties{" +
"name='" + name + '\'' +
", age=" + age +
", demoname='" + demoname + '\'' +
'}';
}
}
yaml 文件
demoapp:
name: demo
age: 333
参考资料
https://www.baeldung.com/spring-boot-testing-configurationproperties
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html
https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/reference/html/boot-features-external-config.html
https://github.com/rongfengliang/pf4j-spring-learning/tree/classloader-test