Aspect Advice для Spring Data Repository не работает
Я пытаюсь создать несколько точек и раньше советов для репозиториев, чтобы включить фильтрацию по EntityManager для некоторых репозиториев в Spring Data в Spring Boot. У меня также есть веб и сервисный слой в проекте, и AspectLogging работает для обоих. Но я не мог сделать то же самое для хранилищ. Я боролся в течение 2 дней, и я пытался так много вещей, чтобы исправить это. Я прочитал почти все документы, проблемы и темы об этом (проблемы с прокси CGlib и JDK Proxy и т. д.). Я использовал Jhipster для создания проекта.
Я не могу развернуть приложение, кроме @Pointcut с CrudRepository. и даже развернутый @Before не вызывается для вызова метода в репозитории. Я думаю, у меня есть похожая проблема, как в следующем вопросе.путаница с доверенностью
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.zzz.business.repository.ApplyRepository com.xxx.zzz.web.rest.applyResource.ApplyRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applyRepository': Post-processing of FactoryBean's singleton object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy173]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy173
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 61 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applyRepository': Post-processing of FactoryBean's singleton object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy173]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy173
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:116)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1523)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:314)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 63 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy173]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy173
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:212)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:447)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:333)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1719)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:113)
... 70 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy173
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:56)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
... 77 more
Кто-нибудь знает, что это может быть?
Классы и конфигурации выглядят следующим образом.
Repository:
public interface ApplyRepository extends JpaRepository<Apply,Long>,QueryDslPredicateExecutor<Apply> {
public Page<Apply> findAll(Predicate predicate, Pageable p);
}
...
}
Конфигурация базы данных:
@Configuration
@EnableJpaRepositories("com.xxx.zzz.business.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement//(proxyTargetClass = false)
public class DatabaseConfiguration {
....
AspectJ Config:
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
// @EnableLoadTimeWeaving(aspectjWeaving = ... )
public class LoggingAspectConfiguration {
...
Архитектура системы:
@Aspect
public class SystemArchitecture {
/**
* A join point is in the web layer if the method is defined
* in a type in the com.xyz.someapp.web package or any sub-package
* under that.W
*/
@Pointcut("within(com.xxx.zzz.web.rest..*)")
public void inWebLayer() {
}
/**
* A join point is in the service layer if the method is defined
* in a type in the com.xyz.someapp.service package or any sub-package
* under that.
*/
@Pointcut("within(com.xxx.zzz.business.service..*)")
public void inServiceLayer() {
}
/**
* A join point is in the data access layer if the method is defined
* in a type in the com.xyz.someapp.dao package or any sub-package
* under that.
*/
@Pointcut("within(com.xxx.zzz.business.repository..*)")
public void inDataAccessLayer() {
}
/**
* All layers
*/
@Pointcut("inWebLayer() || inServiceLayer() || inDataAccessLayer()")
public void inALL(){
}
@Pointcut("within(org.springframework.data.repository.CrudRepository)")
//@Pointcut("execution(*org.springframework.data.repository.Repository+.* (..))")
//@Pointcut("execution(* com.xxx.zzz.business.repository+.*(..))")
//@Pointcut("execution(* org.springframework.data.jpa.repository.JpaRepository+.*(..))")
//@Pointcut("execution(* com.xxx.zzz.business.repository.ApplyRepository.*(..))")
public void inDATAExec(){}
}
FilterAspect:
@Aspect
@Transactional
public class FilterAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@PersistenceContext
private EntityManager entitymanager;
@Before("com.xxx.zzz.aop.logging.SystemArchitecture.inDATAExec())") // "execution(* com.xxx.zzz.business.repository.InvoiceRepository.*(..))"
public void doAccessCheck() {
if (TransactionSynchronizationManager.isActualTransactionActive() && SecurityUtils.isAuthenticated()) {
Session session = entitymanager.unwrap(Session.class);
session.enableFilter("GLOBAL_FILTER").setParameter("customerId", SecurityUtils.getCurrentCustomerId());
}
}
РЕДАКТИРОВАТЬ: я решил проблему. это было как-то связано с неправильными точечными надписями и именами. я пытался изменить pointcuts для пользовательских аннотаций в репозитории. это не работает для метода или уровня класса. Я прочитал в следующих ссылках вопросы об этом.совет 1совет 2 я бьюсь часами за цель и аннотацию. но нет результата. действительно ли невозможно добавить пользовательские аннотации в репозитории Spring Data для рекомендаций?
Аннотация:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
//@Inherited
public @interface CustomerRequired {
String value() default "customerrequired";
}
Repository:
public interface InvoiceRepository extends JpaRepository<Invoice,String>, QueryDslPredicateExecutor<Invoice> {
@CustomerRequired
public Page<Invoice> findAll(Predicate predicate, Pageable p);
...
}
Pointcut и советы:
@Pointcut(value = "@target(customerRequired)",argNames = "customerRequired")
public void targetCustomer(@SuppressWarnings("unused") CustomerRequired customerRequired) {/**/}
@Before(value = "com.xxx.zzz.aop.logging.SystemArchitecture.targetCustomer(customerRequired) && com.xxx.zzz.aop.logging.SystemArchitecture.inDataLayer()")
public void doAccessCheck(JoinPoint joinPoint, CustomerRequired customerRequired) {
if (TransactionSynchronizationManager.isActualTransactionActive() && SecurityUtils.isAuthenticated()) {
Session session = entitymanager.unwrap(Session.class);
session.enableFilter("GLOBAL_FILTER").setParameter("customerId", SecurityUtils.getCurrentCustomerId());
}
}