以下摘自XML应用程序上下文定义显示了我如何在其上调优JDBC DataSource
和Hibernate SessionFactory
:
<context:component-scan base-package="com.phoneBook.dao" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/postgres?currentSchema=phoneBook" />
<property name="username" value="postgres" />
<property name="password" value="a1f10g" />
<property name="initialSize" value="20" />
<property name="maxActive" value="100"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.PostgreSQL94Dialect
</value>
</property>
<property name="annotatedClasses">
<list>
<value>com.phoneBook.model.Address</value>
<value>com.phoneBook.model.Contact</value>
<value>com.phoneBook.model.User</value>
<value>com.phoneBook.model.Lang</value>
</list>
</property>
</bean>
<bean id="myProductDao" class="com.phoneBook.dao.Impl.AddressDaoImpl">
<property name="sessionFactoryBean" ref="mySessionFactory"/>
</bean>
并基于此上下文创建了我的dao类,其中一部分显示在下面
package com.phoneBook.dao.Impl;
@Repository
public class AddressDaoImpl implements AddressDao{
private Session currentSession;
private Transaction currentTransaction;
private LocalSessionFactoryBean sessionFactoryBean;
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return (SessionFactory) sessionFactoryBean.getObject();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public LocalSessionFactoryBean getSessionFactoryBean() {
return sessionFactoryBean;
}
public void setSessionFactoryBean(LocalSessionFactoryBean sessionFactoryBean) {
this.sessionFactoryBean = sessionFactoryBean;
}
但是当我运行我的测试时我有NPE,有人可以解释我做错了吗
@Test
public void addressTest(){
AddressDaoImpl addressDao = new AddressDaoImpl();
try {
addressDao.openSessionWithTransaction();
System.out.print(addressDao.findById(1).toString());
addressDao.openSessionWithTransaction();
} catch (DataBaseException e) {
addressDao.closeSessionWithTransaction();
e.printStackTrace();
}
答案 0 :(得分:0)
您必须在测试用例中自动装配AddressDaoImpl:
@Test
public void addressTest(){
@Autowired
AddressDaoImpl addressDao
或者更好地使用界面:
@Test
public void addressTest(){
@Autowired
AddressDao addressDao
不要忘记用以下方式运行测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:<your configuration>")
因为Autowiering仅适用于Container托管bean,而不是您使用new
关键字创建Bean。