【问题标题】:Unable to implement SpringSecurity-Hibernate simplest example无法实现 Spring Security-Hibernate 简单示例
【发布时间】:2012-03-13 15:54:32
【问题描述】:

我正在阅读 Spring login form example 和 Spring Security 的许多其他帖子来创建登录示例,但我无法准备任何简单的示例。

我试图从这篇帖子 Spring login form example 中整合解决方案 但问题是我希望将 Hibernate 会话工厂注入到 UserDAO 中,以便我可以编写查询以从表中获取用户名。 @Autowire 不工作 所以我用了

<context:annotation-config />
    <context:component-scan
        base-package="com.tcs.ceg" />

但现在我遇到了运行时异常,因为找不到匹配的 bean 无法自动装配 sessionFactory。 但是我在 applicationContext.xml 中创建了一个具有此名称的 bean。 谁能告诉我如何注入 sessionFactory? 我的应用程序-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

【问题讨论】:

  • 请显示来自 UserServiceImpl 的代码。
  • @nico-ekito 我已经添加了代码..请检查并告诉我..
  • 请查看完整的堆栈跟踪。

标签: security hibernate spring


【解决方案1】:

我认为你的 DAO 的 sessionFactory 属性必须是 LocalSessionFactoryBean 类型。

编辑:

在你的 applicationContext.xml 文件中,你已经声明了这个 bean:

<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>

这是一个org.springframework.orm.hibernate3.LocalSessionFactoryBean

那么,在你的 DAO 中,sessionFactory 是一个org.hibernate.SessionFactory

所以我认为 Spring 无法在 DAO 中自动装配您的 bean,因为它不是同一类型。

【讨论】:

  • 这不是问题。 LocalSessionFactoryBean 是在 Spring 应用程序中配置 SessionFactory 的正确方法。
  • 我已经通过引用此链接stackoverflow.com/questions/8319115/… 解决了这个问题,但我无法发布完整的答案,因为我的声誉低于 100 :( ..其他面临此问题的人以任何方式将您的所有配置放在一个根上下文并初始化此链接中提到的所有内容..一切都会起作用
猜你喜欢
  • 2013-01-09
  • 2018-08-06
  • 2021-08-08
  • 2014-10-30
  • 2014-03-14
  • 2016-07-10
  • 1970-01-01
  • 2015-07-17
  • 2019-08-13
相关资源
最近更新 更多