一、spring引入外部属性配置文件
@Data
@ToString
public class MyDataSource implements DataSource {
private String driver;
private String url;
private String name;
private String password;
@Override
public Connection getConnection() throws SQLException {
return null;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
jdbc配置文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring6
name=root
password=123456
spring核心配置文件
<?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 http://www.springframework.org/schema/context/spring-context.xsd">
<!--引入外部的properties文件
引入context命名空间-->
<context:property-placeholder location="jdbc.properties"/>
<bean id="data" class="com.cjc.spring6.jdbc.MyDataSource">
<!--进行取值-->
<property name="driver" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="name" value="${name}"></property>
<property name="password" value="${password}"></property>
</bean>
</beans>
测试代码:
@Test
public void getPro(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springData.xml");
MyDataSource data = applicationContext.getBean("data", MyDataSource.class);
System.out.println(data);
}
测试结果: