改进方法,直接spring注入
java">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 {@Beanpublic 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;}}
调用
java"> @Autowiredprivate 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-genbase-package: com.my.testlocal-java-path: D:\idea_workspace_mygitee\code-gen\mapstruct-mybatis-plus\java-code-gen\src\main\java- name: service-gen2base-package: com.my.testlocal-java-path: D:\idea_workspace_mygitee\code-gen\mapstruct-mybatis-plus\java-code-gen\src\main\java- name: service-gen3base-package: com.my.testlocal-java-path: D:\idea_workspace_mygitee\code-gen\mapstruct-mybatis-plus\java-code-gen\src\main\java
载入yml的配置类
java">
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 {@Beanpublic YamlMapFactoryBean myData(){YamlMapFactoryBean yml = new YamlMapFactoryBean();yml.setResources(new ClassPathResource("my-data.yml"));return yml;}
}
接受数据DTO
java">@Data
public class MyDataCfg {private List<MyDataDTO> data;
}
java">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通过名字注入
java">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);