spring解析xml,yml配置文件
2023-09-11 14:16:49 时间
1 解析xml文件
xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="jdbc.driver">com.mysql.jdbc.Driver</entry>
<entry key="jdbc.url">jdbc:mysql://localhost:3306/spring</entry>
<entry key="jdbc.username">root</entry>
<entry key="jdbc.password">123456</entry>
</properties>
添加注解@PropertySource("classpath:jdbc.xml")
下面的2个图为它的执行流程
但是不推荐xml,虽然结构比较清楚,但是规范太严格了,写起来也很麻烦。
2 解析yml文件
之前博客也写过简单的解析yml文件,那个是参考官网的,但是感觉没有这个灵活,具体如下:
yml文件:
jdbc:
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring
username: root
password: 123456
pom.xml
<!-- yaml解析器 https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
主类:
/**
* @author WGR
* @create 2020/9/16 -- 16:09
*/
public class CustomerPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
//1.创建yaml文件解析工厂
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
//2.设置资源内容
yaml.setResources(resource.getResource());
//3.解析成properties文件
Properties properties = yaml.getObject();
//4.返回符合spring的PropertySource对象
return name != null ? new PropertiesPropertySource(name, properties) : new PropertiesPropertySource(resource.getResource().getFilename(), properties);
}
}
/**
* @author WGR
* @create 2020/9/14 -- 20:41
*/
@Configuration
@Import(JdbcConfig.class)
//@PropertySource("classpath:jdbc.xml")
@PropertySource(value="classpath:jdbc.yml",factory=CustomerPropertySourceFactory.class)
public class SpirngIocConfigure {
}
测试:
相关文章
- java解析XML saxReader.read(xml) 错误:org.dom4j.DocumentException: no protocol
- CS 3600 Intro to Artificial Intelligence — Spring 2020
- 解决IDEA使用Spring Initializr创建项目时,无法连接到https://start.spring.io的问题
- org.codehaus.xfire.fault.XFireFault: Could not read XML stream.. Nested exception is javax.xml.strea
- SSM(Spring+SpringMVC+Mybatis)极简整合完整示例(结构清晰三大框架仅需一个xml配置文件!)
- [转] Spring注解@Component、@Repository、@Service、@Controller区别
- Spring Cloud Feign 请求添加headers(转载)
- spring boot + shiro + redis 整合(完整)
- 我为什么放弃Spring Boot 中的 RestTemplate?选择 Retrofit
- Spring事务传播问题小案例
- Sring源码解析(一)Spring是怎么读取配置Xml文件的
- spring整合activemq发送MQ消息[Topic模式]实例
- eclipse下spring相关xml配置文件导入本地约束
- Spring集成Redis集群(含spring集成redis代码)
- spring.xml从外部文件引入数据库配置信息
- web.xml是tomcat和spring间的桥梁,是tomcat构建spring运行环境的说明书
- Spring MVC 学习笔记 spring mvc Schema-based configuration
- spring框架漏洞整理(Spring Cloud Config路径穿越导致的信息泄露)
- spring框架漏洞整理(Spring Boot Actuator相关漏洞)
- Spring注解开发(常用注解的用法)
- Spring之c3p0连接池xml配置和使用举例
- Spring Boot @Value 在 @Bean 中为null的问题
- Spring中@Conditional注解详细讲解及示例
- 【转】Spring学习---Bean配置的三种方式(XML、注解、Java类)介绍与对比
- 【Spring四】AOP之XML配置
- 【spring框架】通过XML配置事务(Transaction)
- spring源码分析之spring注解@Aspect是如何工作的?
- spring IOC(Spring 生命周期,先1.构造方式,2,初始化方法,3,目标方法,4,销毁方法)