property place holder(属性占位符)

 

 

具体文件格式

 

 

 

db.properties

#键=值

jdbc.driverClassName = com.mysql.jdbc.Driver

jdbc.url = jdbc:mysql:// localhost:3306 / springdemo?rewriteBatchedStatements = true

jdbc.username = root

jdbc.password = 123456

jdbc.maxActive = 5

 

为什么在db.properties里加上JDBC,防止系统读取用户名的时候读取为系统的用户名,而不是读取数据库的用户名

解决办法:

第一种:context命名空间加上system-properties-mode =“从不”

< context :property-placeholder location =“classpath:db.properties” system-properties-mode =“NEVER” >

</ context :property-placeholder >

第二种:

加上JDBC。

 

 

application.xml中

<?xml version =“1.0” encoding =“UTF-8” ?>

< beans xmlns =“ http://www.springframework.org/schema/beans

xmlns:context =“ http://www.springframework.org/schema/context

xmlns:xsi =“ http://www.w3.org/2001/XMLSchema-instance

 

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 >

<! - 引入属性配置文件- >

< context :property-placeholder location =“classpath:db.properties” > </ context :property-placeholder >

<! - 配置连接池- >

< bean id =“datasource” class =“com.alibaba.druid.pool.DruidDataSource” init-method =“init” destroy-method =“close” >

< property name =“driverClassName” value =“$ {jdbc.driverClassName}” > </ property >

< property name =“url” value =“$ {jdbc.url}” > </ property >

< property name =“username” value =“$ {jdbc.username}” > </ property >

< property name =“password” value =“$ {jdbc.password}” > </ property >

< property name =“maxActive” value =“$ {jdbc.maxActive}” > </ property >

</ bean >

 

</ beans >

 

 

 

测试测试类

包装测试;

 

import com.alibaba.druid.pool.DruidDataSource;

import org.junit。测试 ;

import org.junit.runner。RunWith ;

import org.springframework.beans.factory.annotation。自动装配 ;

import org.springframework.test.context。ContextConfiguration ;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 

import javax.sql.DataSource;

import java.sql.Connection;

import java.sql.SQLException;

 

@RunWith(SpringJUnit4ClassRunner .class

@ContextConfiguration“classpath:applicationContext.xml”

公共课考试{

@Autowired

private DataSource dataSource ;

@测试

public void test()抛出 Exception {

 

Connection conn = dataSource .getConnection();

系统。out .println(conn);

}

}

 

 

 

测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值