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 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
    • ¥15 操作系统相关算法中while();的含义
    • ¥15 CNVcaller安装后无法找到文件
    • ¥15 visual studio2022中文乱码无法解决
    • ¥15 关于华为5g模块mh5000-31接线问题
    • ¥15 keil L6007U报错
    • ¥15 webapi 发布到iis后无法访问
    • ¥15 初学者如何快速上手学习stm32?
    • ¥15 如何自动更换布娃娃图片上的衣服
    • ¥15 心理学eprime编程