错误
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文件
mysql-username=root
mysql-password=abcd2020
mysql-jdbcUrl=jdbc:mysql://192.168.3.16/beers
mysql-driverClass=com.mysql.jdbc.Driver
Java的测试类
package com.mars.springtest;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.sql.SQLException;
public class BeerTest {
ConfigurableApplicationContext ioc=new ClassPathXmlApplicationContext("db-config.xml");
@Test
public void test() throws SQLException {
DataSource bean= (DataSource) ioc.getBean("mysql-pool");
System.out.println(bean.getConnection());
}
}
出错时的spring的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:contest="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<contest:property-placeholder location="classpath:db-config.properties"/>
<bean id="mysql-pool" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${mysql-username}"></property>
<property name="password" value="${mysql-password}"></property>
<property name="jdbcUrl" value="${mysql-jdbcUrl}"></property>
<property name="driverClass" value="${mysql-driverClass}"></property>
</bean>
</beans>
更正之后的spring的配置文件。注意红色的两行默认是没有,加上这两行就Ok了
<?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:contest="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">
<contest:property-placeholder location="classpath:db-config.properties"/>
<bean id="mysql-pool" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${mysql-username}"></property>
<property name="password" value="${mysql-password}"></property>
<property name="jdbcUrl" value="${mysql-jdbcUrl}"></property>
<property name="driverClass" value="${mysql-driverClass}"></property>
</bean>
</beans>
后记
2020年2月21日 农历正月2020年正月二八 星期五 凌晨3点 上海 晴