无法实现SpringSecurity-Hibernate最简单的例子
我正在阅读以下帖子 Spring 登录表单示例 以及 Spring Security 的许多其他帖子来创建一个登录示例,但我无法准备任何简单的示例。
我试图合并这篇文章中的解决方案 Spring 登录表单示例 但问题是我希望将 Hibernate 会话工厂注入到 UserDAO 中,以便我可以编写查询来从表中获取 userName。 @Autowire 不起作用 所以我使用了
<context:annotation-config />
<context:component-scan
base-package="com.tcs.ceg" />
,但现在我收到运行时异常,因为无法自动装配 sessionFactory,因为没有找到匹配的 bean。 但是我在 applicationContext.xml 中创建了一个具有此名称的 bean。 谁能告诉我如何注入sessionFactory? 我的 application-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
">
<context:annotation-config />
<context:component-scan
base-package="com.tcs.ceg" />
<global-method-security pre-post-annotations="enabled" />
<http pattern="/css/**" security="none"/>
<http pattern="/images/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/index.jsp" security="none"/>
<http pattern="/loggedout.jsp" security="none"/>
<http use-expressions="true">
<!--
Allow all other requests. In a real application you should
adopt a whitelisting approach where access is not allowed by default
-->
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login />
<logout logout-success-url="/loggedout.jsp" delete-cookies="JSESSIONID"/>
<remember-me />
</http>
<beans:bean id="myUserService" class="com.tcs.ceg.services.impl.UserServiceImpl" />
<authentication-manager>
<authentication-provider user-service-ref="myUserService" />
</authentication-manager>
</beans:beans>
和我的 applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" >
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan
base-package="com.tcs.ceg" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<jee:jndi-lookup id="dataSource1" jndi-name="jdbc/PmdDS"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1000000000000"/>
</bean>
</beans>
UserServiceImpl 的代码
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tcs.ceg.dao.intrface.UserDao;
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private transient UserDao userDao;//userDao is null
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
@Transactional
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user=null;
try{
user = userDao.getUser(username);
}catch(Exception err){
err.printStackTrace();
}
if (user != null) {
// convert roles
// initialize user
return user;
} else {
throw new UsernameNotFoundException("No user with username '" + username + "' found!");
}
}
}
UserDaoImpl 的代码
import java.util.ArrayList;
import java.util.Collection;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Repository;
import com.tcs.ceg.dao.intrface.UserDao;
import com.tcs.ceg.util.lib.DbComparisonException;
@Repository
public class UserDaoimpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;//sessionfactory is null
@Override
public User getUser(String username) throws DbComparisonException {
String password = "rajesh";
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("admin"));
User user = new User(username, password, enabled,
accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return user;
}
}
请注意,我没有在 UserDaoimpl 中编写以下行,因为 sessionFactory 为空
sessionFactory.getCurrentSession().createQuery("from User").list();//throws null pointer exception
I was going through following post Spring login form example and many other post of Spring Security to create a login example but I was not able to prepare any simple example.
I was trying to incorporate solution from this post Spring login form example
but problem is that I want Hibernate session factory to be injected in the UserDAO so that I can write query to get userName from table. @Autowire is not working
so I used
<context:annotation-config />
<context:component-scan
base-package="com.tcs.ceg" />
but now i am getting runtime exception as cannot autowire sessionFactory as no matching bean found.
But a bean with this name I have created in my applicationContext.xml .
Can anyone tell me how can I inject sessionFactory?
my application-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
">
<context:annotation-config />
<context:component-scan
base-package="com.tcs.ceg" />
<global-method-security pre-post-annotations="enabled" />
<http pattern="/css/**" security="none"/>
<http pattern="/images/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/index.jsp" security="none"/>
<http pattern="/loggedout.jsp" security="none"/>
<http use-expressions="true">
<!--
Allow all other requests. In a real application you should
adopt a whitelisting approach where access is not allowed by default
-->
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login />
<logout logout-success-url="/loggedout.jsp" delete-cookies="JSESSIONID"/>
<remember-me />
</http>
<beans:bean id="myUserService" class="com.tcs.ceg.services.impl.UserServiceImpl" />
<authentication-manager>
<authentication-provider user-service-ref="myUserService" />
</authentication-manager>
</beans:beans>
and my applicationContext.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" >
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan
base-package="com.tcs.ceg" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<jee:jndi-lookup id="dataSource1" jndi-name="jdbc/PmdDS"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1000000000000"/>
</bean>
</beans>
Code for UserServiceImpl
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tcs.ceg.dao.intrface.UserDao;
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private transient UserDao userDao;//userDao is null
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
@Transactional
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user=null;
try{
user = userDao.getUser(username);
}catch(Exception err){
err.printStackTrace();
}
if (user != null) {
// convert roles
// initialize user
return user;
} else {
throw new UsernameNotFoundException("No user with username '" + username + "' found!");
}
}
}
Code for UserDaoImpl
import java.util.ArrayList;
import java.util.Collection;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Repository;
import com.tcs.ceg.dao.intrface.UserDao;
import com.tcs.ceg.util.lib.DbComparisonException;
@Repository
public class UserDaoimpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;//sessionfactory is null
@Override
public User getUser(String username) throws DbComparisonException {
String password = "rajesh";
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("admin"));
User user = new User(username, password, enabled,
accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return user;
}
}
Please note i havent written following line in UserDaoimpl because sessionFactory is null
sessionFactory.getCurrentSession().createQuery("from User").list();//throws null pointer exception
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 DAO 的
sessionFactory
属性必须是LocalSessionFactoryBean
类型。编辑:
在你的applicationContext.xml文件中,你已经声明了这个bean:
它是一个
org.springframework.orm.hibernate3.LocalSessionFactoryBean
。然后,在您的 DAO 中,sessionFactory 是一个 org.hibernate.SessionFactory。
所以我认为 Spring 无法在 DAO 中自动装配你的 bean,因为它不是同一类型。
I think that the
sessionFactory
attribute of your DAO must be of typeLocalSessionFactoryBean
.EDIT :
In your applicationContext.xml file, you have declared this bean :
which is a
org.springframework.orm.hibernate3.LocalSessionFactoryBean
.Then, in your DAO, sessionFactory is a
org.hibernate.SessionFactory
.So I think that Spring is unable to autowire your bean in the DAO since it is not the same type.