以上是架构,在applicationContext.xml中,配置读取jdbc.properties,但是tomcat启动项目时,会出现以下的报错。
applicationContext.xml代码如下:
<!-- 引入外部文件,读取jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>
jdbc.properties配置如下:
jdbc.url=jdbc:mysql://localhost:3306/ssmdemo?characterEncoding=utf-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
启动tomcat后的报错信息如下,出现了不能成功拿到jdbc配置信息的问题:
23:39:33,563 INFO PropertySourcesPlaceholderConfigurer:172 - Loading properties file from class path resource [jdbc.properties]
23:39:33,563 DEBUG MutablePropertySources:109 - Adding [localProperties] PropertySource with lowest search precedence
23:39:33,566 DEBUG JndiTemplate:150 - Looking up JNDI object with name [java:comp/env/jdbc.url]
23:39:33,567 DEBUG JndiLocatorDelegate:101 - Converted JNDI name [java:comp/env/jdbc.url] not found - trying original name [jdbc.url]. javax.naming.NameNotFoundException: Name [jdbc.url] is not bound in this Context. Unable to find [jdbc.url].
23:39:33,567 DEBUG JndiTemplate:150 - Looking up JNDI object with name [jdbc.url]
在查阅了很多资料之后,发现在web.xml文件中,加入以下代码,就可以解决上述问题,亲测有效。
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.liveBeansView.mbeanDomain</param-name>
<param-value>dev</param-value>
</context-param>