改进方法,直接spring注入
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import java.util.Map;
@Configuration
public class MyDataYml {
@Bean
public MyDataCfg myData(){
YamlMapFactoryBean yml = new YamlMapFactoryBean();
yml.setResources(new ClassPathResource("my-data.yml"));
Map<String, Object> map = yml.getObject();
MyDataCfg project = JSONUtil.parse(map.get("project")).toBean(MyDataCfg.class);
return project;
}
}
调用
@Autowired
private MyDataCfg myData;
json解析的pom引入
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<version>5.8.20</version>
</dependency>
resources目录下的my-data.yml
project:
data:
- name: service-gen
base-package: com.my.test
local-java-path: D:\idea_workspace_mygitee\code-gen\mapstruct-mybatis-plus\java-code-gen\src\main\java
- name: service-gen2
base-package: com.my.test
local-java-path: D:\idea_workspace_mygitee\code-gen\mapstruct-mybatis-plus\java-code-gen\src\main\java
- name: service-gen3
base-package: com.my.test
local-java-path: D:\idea_workspace_mygitee\code-gen\mapstruct-mybatis-plus\java-code-gen\src\main\java
载入yml的配置类
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
public class MyDataYml {
@Bean
public YamlMapFactoryBean myData(){
YamlMapFactoryBean yml = new YamlMapFactoryBean();
yml.setResources(new ClassPathResource("my-data.yml"));
return yml;
}
}
接受数据DTO
@Data
public class MyDataCfg {
private List<MyDataDTO> data;
}
import cn.hutool.core.annotation.Alias;
import lombok.Data;
@Data
public class MyDataDTO {
@Alias("name")
private String name;
@Alias("base-package")
private String basePackage;
@Alias("local-java-path")
private String localJavaPath;
}
调用
spring通过名字注入
import cn.hutool.json.JSONUtil;
import javax.annotation.Resource;
import java.util.Properties;
@Resource(name = "myData")
private Properties p;
MyDataCfg project = JSONUtil.parse(p.get("project")).toBean(MyDataCfg.class);