java - Spring AOP和Spring JPA,要执行的Aspect

标签 java spring aspectj spring-data spring-aop

我一直在编写一个方面来操纵我的一些 JPA 实体 getter。它应该根据客户的语言环境重新格式化返回的文本。因为不是所有的 getter 都应该重新格式化,所以我引入了注释 @ReFormat

问题是当我向 JPA 实体建议我的方面时,我的方面从未被拦截,但它在非 JPA 实体上工作正常(当我通过复制构造函数创建我自己的实体对象时它工作)。

我的注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface ReFormat {

}

我的方面:

@Aspect
public class ReFormatAspect {
    @AfterReturning(pointcut = "@annotation(com.path.ReFormat)", returning = "response")
    public Object formatter(JoinPoint joinPoint, Object response) {
       return response;
    }
}

现在这个方面在我的 MVC Controller (或除 spring 数据之外的任何其他地方)中被成功拦截,但对于我的实体却没有。

@Entity
@Table(name = "place", schema = "db")
public class TestEntity {

   @Id
   @Column(name = "id")
   protected long id;

   @Column(name = "about", columnDefinition = "TEXT DEFAULT NULL")
   protected String about;

   @ReFormat
   public String getAbout() {
       return this.about;
   }

我希望在调用 getAbout 方法后切入点,但它不起作用。

鉴于上述事实,我认为 JPA (Hibernate) 正在覆盖任何可能由 CGLib 或 javassist 提供的拦截器。

注意:我的上下文中有这个

<context:annotation-config />
<context:spring-configured />
<aop:aspectj-autoproxy proxy-target-class="true" />

那么确切的问题是什么,我该如何拦截实体内的任何方法?

我明白这应该是 View 层的工作,但我仍然需要知道为什么 :D

最佳答案

您的实体不由 Spring 管理,它们由底层 JPA 实现管理。因此,Spring 无法将它们包装在代理中并提供所需的行为。

Spring 没有办法解决这个问题。 Hibernate 可能有一些拦截器工具(在创建时包装实体)但我不知道。也许扩展 EmptyInterceptor .

关于java - Spring AOP和Spring JPA,要执行的Aspect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18533983/

相关文章:

java - 无法从 java main 方法调用 build.xml

java - JPA 映射中的错误 - 获取注释

java - 将 long 的最大值分配给 long 类型会引发异常

java - 如何使用 spring-ws 记录未处理的异常

java - 方面破坏特定类上的字节码

java - 如何修复 : My Web App forces all users to "interact" with the same list,,而不是为每个用户提供自己的列表

spring - 包名不包含 ObjectFactory.class 或 jaxb.in​​dex

java - 使用 Hibernate + MySQL 保存或更新多对多表

java - 使用 AspectJ 拦截请求范围内的所有 JDBC 调用并作为响应返回

java - 使用 AspectJ LTW 时的 Spring 缓存问题