2017-03-17 104 views
0

我试图启用一个使用Spring AOP和Spring Boot的Hibernate过滤器。我用这个帖子作为启动点:How to enable hibernate filter for sessionFactory.getCurrentSession()?如何使用AOP和Spring Boot启用休眠过滤器?

到目前为止,我还没有能够拦截Hibernate会话:org.hibernate.internal.SessionFactoryImpl.SessionBuilderImpl.openSession()。

我的切面类看起来是这样的:

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.AfterReturning; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before; 
import org.hibernate.Session; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.security.core.Authentication; 
import org.springframework.security.core.context.SecurityContextHolder; 
import org.springframework.stereotype.Component; 

import com.acme.CustomUserDetails; 

@Component 
@Aspect 
public class ACLFilter { 
    Logger log = LoggerFactory.getLogger(ACLFilter.class); 

    @AfterReturning(pointcut = "execution(* org.hibernate.internal.SessionFactoryImpl.openSession(..)))", returning = "session") 
    public void forceFilter(JoinPoint joinPoint, Object session) { 
     Session hibernateSession = (Session) session; 
     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     Long userId = ((CustomUserDetails) auth.getDetails()).getUserId(); 
     // Session session = em.unwrap(Session.class); 
     hibernateSession.enableFilter("groupACL").setParameter("userId", userId); 
    } 

    @Before("execution(* org.hibernate.SessionFactory.openSession(..)))") 
    public void do2(JoinPoint joinPoint) { 
     System.out.println("############################do2"); 
    } 

    @Before("execution(* org.hibernate.SessionBuilder.openSession(..)))") 
    public void do3(JoinPoint joinPoint) { 
     System.out.println("############################do3"); 
    } 

    @Before("execution(* org.hibernate.internal.SessionFactoryImpl.SessionBuilderImpl.openSession(..)))") 
    public void do4(JoinPoint joinPoint) { 
     System.out.println("############################do4"); 
    } 

} 

这是所有的类/方法我试图拦截。我还验证了方面类正在使用测试类/方法正常工作,并且它的确如此,所以AOP设置是正确的。 在调试时我可以看到系统触发org.hibernate.internal.SessionFactoryImpl.SessionBuilderImpl.openSession() ,但不会触发我的拦截器? 我application.properties文件包含此项:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext 

我缺少什么?

+0

请小心选择适合语法高亮显示的语言。你的代码不是JavaScript + HTML,而是Java。我已经为你修好了。 – kriegaex

回答

1

Hibernate类不是Spring组件,因此Spring AOP不适用于它们。如果你想拦截他们,我建议你切换到完整AspectJ with load-time weaving。然后你也可以选择不使用execution()来操作Hibernate的字节码,但是call()只会改变你自己的类。