Spring 从入门到精通 (九) 配置文件参数化
关键词:Spring | 配置文件 | 参数化
一、概念
配置文件参数化是指把Spring配置文件中经常需要修改的字符串信息,单独提取转移到一个小配置文件中。
二、有经常修改的配置吗?
有啊,比如数据库相关的配置
三、为什么要转移?
有人又称Spring项目为 配置地狱 ,其实就是真实项目Spring配置可能会达到几千行甚至更多,此时去修改一些参数,比如数据库配置相关的,就非常不利于维护,因此,希望能把它单独抽取出来,放在一个单独的小配置文件中(properties),利于项目维护。
四、开发
开发思路
首先准备好要转移常用字符串的小配置文件,然后通过配置告诉spring咱使用了小配置文件,并指定是哪一个,通过一些特殊配置完成开发。
首先,准备一个小的配置文件(properties),名字没要求,位置没要求
driverClassName = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/zhou?useSSL=false username = root password = root
Spring中配置 <context:property-placeholder location="小配置文件位置"/>,这里注意使用了classpath,这里的这个是什么意思呢?就是指类路径,类路径又是哪呢,哈哈,这个问题问得好,这就要根据情况说了,在Maven项目中,根据Maven的目录和打包机制,会将Java目录和resources目录打包在同一目录下,这也就是所谓的classpath类路径,具体的可以看打包后的目录结构如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:db.properties"/> <bean id="conn" class="factorybean.ConnectionFactoryBean"> <property name="driverClassName" value="${driverClassName}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean> </beans>
测试,尝试获取连接对象,如果成功获取,说明配置文件参数化成功,否则失败。
@Test public void t7() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("newspring.xml"); Connection conn = (Connection) context.getBean("conn"); System.out.println(conn); }
成功拿到,没有问题
com.mysql.jdbc.JDBC4Connection@19b2141
五、写在最后
座右铭:不要在乎别人如何看你,要在乎你自己如何看未来,看梦想,看世界…!