错误
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 17 in XML document from class path resource [db-config.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 78; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'contest:property-placeholder'.
保存数据库用户名等信息的properties文件
1mysql-username=root 2mysql-password=abcd2020 3mysql-jdbcUrl=jdbc:mysql://192.168.3.16/beers 4mysql-driverClass=com.mysql.jdbc.Driver
Java的测试类
1package com.mars.springtest; 2 3import org.junit.Test; 4import org.springframework.context.ConfigurableApplicationContext; 5import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7import javax.sql.DataSource; 8import java.sql.SQLException; 9 10public class BeerTest { 11 ConfigurableApplicationContext ioc=new ClassPathXmlApplicationContext("db-config.xml"); 12 @Test 13 public void test() throws SQLException { 14 DataSource bean= (DataSource) ioc.getBean("mysql-pool"); 15 System.out.println(bean.getConnection()); 16 } 17}
出错时的spring的xml配置文件
1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:contest="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd"> 7 8 9 <contest:property-placeholder location="classpath:db-config.properties"/> 10 <bean id="mysql-pool" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 11 <property name="user" value="${mysql-username}"></property> 12 <property name="password" value="${mysql-password}"></property> 13 <property name="jdbcUrl" value="${mysql-jdbcUrl}"></property> 14 <property name="driverClass" value="${mysql-driverClass}"></property> 15 </bean> 16</beans>
更正之后的spring的配置文件。注意红色的两行默认是没有,加上这两行就Ok了
1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:contest="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd"> 9 10 <contest:property-placeholder location="classpath:db-config.properties"/> 11 <bean id="mysql-pool" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 12 <property name="user" value="${mysql-username}"></property> 13 <property name="password" value="${mysql-password}"></property> 14 <property name="jdbcUrl" value="${mysql-jdbcUrl}"></property> 15 <property name="driverClass" value="${mysql-driverClass}"></property> 16 </bean> 17</beans>

后记
2020年2月21日 农历正月2020年正月二八 星期五 凌晨3点 上海 晴