iteye_11128 2013-11-01 13:31
浏览 149

spring3 + hibernate 4.1 配置的问题

项目用:spring MVC + spring 3.2.4 + Hibernate 4.2.6+spring security3.1.4
在启动容器时,spring security 通过hibernate去数据库加载权限时,报:No Session found for current thread异常。

异常如下:
[code="java"]
Caused by: org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:990)
at com.seveng.weixin.foundation.dao.support.HibernateGenericDao.getSession(HibernateGenericDao.java:58)
at com.seveng.weixin.foundation.dao.support.HibernateGenericDao.getAll(HibernateGenericDao.java:85)
at com.seveng.weixin.foundation.security.filter.support.WeixinInvocationSecurityMetadataSourceService.loadResourceDefine(WeixinInvocationSecurityMetadataSourceService.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:344)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:295)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130)
... 60 more
[/code]

spring MVC 配置文件:spring-mvc.xml
[code="xml"]

<!-- 开启controller注解支持 -->
<context:component-scan base-package="com.seveng.weixin" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

[/code]

spring 主配置文件:
[code="xml"]


/context:component-scan
[/code]

事务的配置:
[code="xml"]


<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="save*" propagation="REQUIRED" />
        <tx:method name="add*" propagation="REQUIRED" />
        <tx:method name="create*" propagation="REQUIRED" />
        <tx:method name="insert*" propagation="REQUIRED" />
        <tx:method name="update*" propagation="REQUIRED" />
        <tx:method name="merge*" propagation="REQUIRED" />
        <tx:method name="del*" propagation="REQUIRED" />
        <tx:method name="remove*" propagation="REQUIRED" />
        <tx:method name="put*" propagation="REQUIRED" />
        <tx:method name="use*" propagation="REQUIRED" />
        <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 -->
        <tx:method name="get*" propagation="REQUIRED" read-only="true" />
        <tx:method name="load*" propagation="REQUIRED" read-only="true" />
        <tx:method name="find*" propagation="REQUIRED" read-only="true" />
        <tx:method name="list*" propagation="REQUIRED" read-only="true" />
        <tx:method name="*" read-only="true" />
    </tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
    <!-- 对业务逻辑层实施事务 -->
    <aop:pointcut id="txPointcut" expression="execution(* com.seveng.weixin..service.impl.*.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
<aop:aspectj-autoproxy expose-proxy="true"/>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />

[/code]

数据库数相关配置:
[code="xml"]
<!-- 加载资源文件 -->

<!-- 数据库映射 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${connection.driver_class}" />
    <property name="url" value="${connection.url}" />
    <property name="username" value="${connection.username}" />
    <property name="password" value="${connection.password}" />
</bean>

<!-- hibernate 需要的信息 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.seveng.weixin.**.model.*</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
            <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
            <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
            <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
            <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop>
            <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
            <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
            <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
            <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
            <prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop>
            <prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop>
            <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
        </props>
    </property>
</bean>

[/code]

spring security 相关配置:
[code="xml"]

<!-- 不拦截的请求 -->
<security:http pattern="/login" security="none" />
<security:http pattern="/images/**" security="none" />
<security:http pattern="/css/**" security="none" />
<security:http pattern="/js/**" security="none" />

<!-- 保护应用程序的所有URL -->
<security:http auto-config="true">

    <!-- login-page: 指定登录页面 -->
    <security:form-login login-page="/login" />
    <security:logout logout-success-url="/login" />

    <!-- 会话管理配置 ,设置最多登录一次,二次登录会让第一次登录失效, 则设置error-if-maximum-exceeded为false,要求第一次有效设置为true -->
    <security:session-management invalid-session-url="/login">
        <security:concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
    </security:session-management>

    <!-- 增加一个自定义的filter,放在FILTER_SECURITY_INTERCEPTOR之前, 实现用户、角色、权限、资源的数据库管理。 -->
    <security:custom-filter ref="weixinFilter" before="FILTER_SECURITY_INTERCEPTOR" />

</security:http>

<!-- 一个自定义的filter,必须包含authenticationManager, accessDecisionManager,securityMetadataSource三个属性。 -->
<bean id="weixinFilter" class="com.seveng.weixin.foundation.security.filter.WeixinFilterSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="accessDecisionManager" ref="weixinAccessDecisionManager" />
    <property name="securityMetadataSource" ref="weixinInvocationSecurityMetadataSourceService" />
</bean>

<!-- 注意能够为authentication-manager 设置alias别名 -->
<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider user-service-ref="appUserDetailsService">
        <security:password-encoder ref="passwordEncoder">
            <security:salt-source user-property="username" />
        </security:password-encoder>
    </security:authentication-provider>
</security:authentication-manager>

<!-- 事件监听:实现了 ApplicationListener监听接口,包括AuthenticationCredentialsNotFoundEvent 事件, AuthorizationFailureEvent事件,AuthorizedEvent事件, PublicInvocationEvent事件 -->
<bean class="org.springframework.security.authentication.event.LoggerListener" />

<!-- 用户的密码加密或解密 -->
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />


<!-- 启用用户的缓存功能 -->
<bean id="userCache" class="org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache">
    <property name="cache" ref="userEhCache" />
</bean>

<bean id="userEhCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
    <property name="cacheName" value="userCache" />
    <property name="cacheManager" ref="cacheManager" />
</bean>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >
    <property name="configLocation" value="classpath:config/ehcache.xml" />
</bean>

[/code]

当容器启动时,spring security加载权限的代码
[code="java"]
@PostConstruct
@Transactional
public void loadResourceDefine() {
List authorities = this.getAll(Authority.class);
// 应当是资源为key, 权限为value。 资源通常为url, 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。
resourceMap = new HashMap>();
for (Authority auth : authorities) {
ConfigAttribute ca = new SecurityConfig(auth.getAuthName());

        Set<Resource> resources = auth.getResources();

        for (Resource res : resources) {
            String url = res.getResString();

            // 判断资源文件和权限的对应关系,如果已经存在相关的资源url,则要通过该url为key提取出权限集合,将权限增加到权限集合中
            if (resourceMap.containsKey(url)) {

                Collection<ConfigAttribute> value = resourceMap.get(url);
                value.add(ca);
                resourceMap.put(url, value);
            } else {
                Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
                atts.add(ca);
                resourceMap.put(url, atts);
            }
        }
    }
}

[/code]

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
    • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
    • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)