項目中數據源採用JNDI的方式,因爲JNDI由容器提供,
因此在跑Junit用例時,必須要先創建一個JNDI才行。
其實用spring創建jndi十分的簡單,首先編寫一個測試用的創建數據源信息的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<beans:property name="url" value="jdbc:oracle:thin:@localhost:1521/test" />
<beans:property name="username" value="developer" />
<beans:property name="password" value="developer" />
</beans:bean>
</beans:beans>
然後直接在代碼中加載創建就可以了,見代碼:
@BeforeClass
public static void beforeClass() throws Exception{
ClassPathXmlApplicationContext app =new ClassPathXmlApplicationContext("classpath:InitJndi.xml");
DataSource ds =(DataSource) app.getBean("dataSource");
SimpleNamingContextBuilder builder =new SimpleNamingContextBuilder();
builder.bind("java:OracleDS", ds);
builder.activate();
}
這樣就成功創建了一個名爲OracleDS的jndi,在跑Junit時就可以獲取到了。
順便附件上spring中獲取jndi的配置:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:OracleDS</value>
</property>
</bean>