介绍spring使用外部属性文件
关键代码:
<!-- 导入属性文件 --> <context:property-placeholder location="user.conf" file-encoding="UTF-8"></context:property-placeholder> <!-- 使用外部属性文件的属性,使用${var}实现 --> <bean id="user" class="com.shuoeasy.test.User" p:id="${id}" p:name="${name}"></bean>
详细:
User.java
package com.shuoeasy.test; public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
bean.xml:
<?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:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- 导入属性文件 --> <context:property-placeholder location="user.conf" file-encoding="UTF-8"></context:property-placeholder> <!-- 使用外部属性文件的属性,使用${var}实现 --> <bean id="user" class="com.shuoeasy.test.User" p:id="${id}" p:name="${name}"></bean> </beans>
Main.java:
package com.shuoeasy.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); User user = (User) ctx.getBean("user"); System.out.println("引用配置->" + user); } }
输出:
引用配置->User [id=1002, name=老鹰开灰机]