自动装配的 sessionFactory 对象为空
Posted
技术标签:
【中文标题】自动装配的 sessionFactory 对象为空【英文标题】:Autowired sessionFactory object is null 【发布时间】:2014-12-17 09:20:28 【问题描述】:在 UesrDAO 类中获取空指针异常作为 sessionFactory 对象始终为空。如果这有帮助,我发现如果使用“new”手动创建 DAO 而不是让 spring 处理它,就会发生这种情况。我没有这样做,我在服务类中注入了 UserDAO,但仍然将 sessionFactory 设置为 null。
感谢您的帮助。
以下是相关文件的内容:
hibernate.cfg.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/properties/database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="$jdbc.driverClassName" />
<property name="url" value="$jdbc.url" />
<property name="username" value="$jdbc.username" />
<property name="password" value="$jdbc.password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.mysqlDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>org.questionbank.dto</value>
</list>
</property>
</bean>
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<import resource="hibernate.cfg.xml"/>
<mvc:annotation-driven />
<tx:annotation-driven />
<context:annotation-config />
<!-- To scan the components -->
<context:component-scan base-package="org.questionbank"/>
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory" />
</bean>
</beans>
DAO 类:
public class UserDAO
protected static Logger logger = Logger.getLogger("dao");
@Autowired
private SessionFactory sessionFactory;
public UserDTO searchDatabase(String username)
logger.debug("Seraching for user in DB");
UserDTO user=new UserDTO();
Query query = sessionFactory.getCurrentSession().createQuery("FROM UserDTO u WHERE u.userName = :userName");
query.setParameter("userName", username);
user = (UserDTO) query.uniqueResult();
if(user!=null)
return user;
logger.error("User does not exist!");
throw new RuntimeException("User does not exist!");
服务类:
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService
protected static Logger logger = Logger.getLogger("service");
@Autowired
private UserDAO userDAO;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException
UserDetails user = null;
try
UserDTO dbUser = userDAO.searchDatabase(username);
user = new User(
dbUser.getUserName(),
dbUser.getPassword().toLowerCase(),
true,
true,
true,
true,
getAuthorities(Integer.parseInt(dbUser.getAccess())));
catch (Exception e)
logger.error("Error in retrieving user");
e.printStackTrace();
throw new UsernameNotFoundException("Error in retrieving user");
return user;
【问题讨论】:
两个组件是否都使用@Component
(或类似的注解,例如@Repository
、@Service
等)进行了注解?另外,它们是否都在org.questionbank
或子包中声明?
你能发布堆栈跟踪吗?
已解决,我在 xml 中没有 UserDAO bean,也没有为它添加注释,添加注释就可以了。感谢@AnthonyAccioly 指出这一点。
OK usercpd。欢迎来到堆栈溢出。我会把它变成一个答案好吗?
【参考方案1】:
您当前的配置,<context:annotation-config />
和 <context:component-scan base-package="org.questionbank"/>
启用了您需要的前半部分功能,以便让 Spring 正确识别和注入您的 bean。
另一半实际上是将 bean 声明为 Spring 管理的组件。
您可以通过以下两种方式之一执行此操作。在applicationContext.xml
中使用<bean />
标记声明bean(就像您对transactionManager
所做的那样)或使用stereotype annotation(例如@Component
、@Repository
、@Service
或@Controller
) .
@Repository
public class UserDAO // ...
和
@Service
public class CustomUserDetailsService // ...
【讨论】:
以上是关于自动装配的 sessionFactory 对象为空的主要内容,如果未能解决你的问题,请参考以下文章