试错笔记
小错误
-
MultipartFile判空操作不能用“==”,而应该用MultipartFile内置的isEmpty()方法,否则达不到判空的目的
-
File类关联文件建议传两个参数 new File(a1,a2),a1表示文件所在目录,a2表示文件名称,直接拼接可能报错,会将文件名称视为文件夹名称,判断文件是否存在时,exists()会返回不存在,暂时不知道原因
-
spring boot不能注入静态变量,对静态变量的@Autowired不起作用
Spring对C3P0数据库连接池注入时出现的问题
- 需要导入2个——3个jar包
mchange-commons-java-0.2.19.jar这是c3p0数据库连接池的辅助包,如果没有这个包系统启动时会报classnotfoundexception,这是更新c3p0-0.9.2版本后分离出来的包,0.9.1的时候还是只是一个包。
如果没有导入这个辅助包,配置bean时,不报错,但是获取容器实例化bean时会报错;
- xml配置c3p0:
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="user" value="root"/>
<property name="password" value=""/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/study"/>
</bean>
- 测试代码:
@Test
public void testDataSource() throws SQLException {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("ioc3.xml");
DataSource dataSource = ac.getBean("datasource",DataSource.class);
System.out.println(dataSource);
}
报错信息:
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'datasource' defined in class path resource [ioc3.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mchange.v2.c3p0.ComboPooledDataSource]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector
//翻译大概意思就是:创建名为'datasource'的bean时出错,该bean在类路径资源[ioc3.xml]中定义:实例化bean失败,为找到默认构造函数
//但是ComboPooledDataSource是有无参构造的,所以可能无法找到准确的错误原因
导入辅助包后正常获取到DataSource:
结果:
信息: Initializing c3p0-0.9.5.5 [built 11-December-2019 22:07:46 -0800; debug? true; trace: 10]
com.mchange.v2.c3p0.ComboPooledDataSource[ identityToken -> 1b61iobahze2bpj1a5zcgw|7fc229ab, dataSourceName -> 1b61iobahze2bpj1a5zcgw|7fc229ab ]
Process finished with exit code 0
引用外部配置文件时需要使用的命名空间context
导入命名空间:
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-4.0.xsd">
如果只导入图中第一行,运行时可能会报以下错误:
Line 8 in XML document from class path resource [ioc4.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 8; columnNumber: 70; cvc-complex-type.2.4.c: 通配符的匹配很全面, 但无法找到元素 'context:property-placeholder' 的声明。