Spring中配置文件中引用外部文件

时间:2021-03-21 21:07:27

src\dayday\conn.java

package dayday;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; /**
* Created by I am master on 2016/11/29.
*/
public class conn {
private String user;
private String password;
private String driveClass;
private String jdbcUrl;
private Connection connection;
public void setUser(String user){
this.user=user;
}
public void setPassword(String password){
this.password=password;
}
public void setDriveClass(String driveClass){
this.driveClass=driveClass;
}
public void setJdbcUrl(String jdbcUrl){
this.jdbcUrl=jdbcUrl;
}
public Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(driveClass);
connection= DriverManager.getConnection(jdbcUrl,user,password);
return connection;
}
}

src\dayday\Main.java

package dayday;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.net.SocketTimeoutException;
import java.sql.SQLException; /**
* Created by I am master on 2016/11/28.
*/
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
conn con=ctx.getBean("conn",conn.class);
System.out.println(con.getConnection());
}
}

src\db.properties

src\beans.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.xsd">
<!--原来的配置方式-->
<!--<bean id="conn" class="dayday.conn">
<property name="driveClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/bank"></property>
</bean>-->
<!--通过外部配置文件进行配-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="conn" class="dayday.conn">
<property name="driveClass" value="${driveClass}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
</bean>
</beans> 运行结果:
com.mysql.jdbc.JDBC4Connection@17942a1
通过<context:property-placeholder location="classpath:db.properties"/>加入外部配置文件
通过${var}引用外部的属性