尽管在表达式中指定了确切的名称,但切入点表达式与Spring Data方法不匹配

时间:2018-11-20 19:00:53

标签: spring-boot spring-data-jpa aop spring-aop

在我的Spring Boot项目中,我有AddressRepository,它可以从数据库中获取所有地址。我有一个Aspect类和一个切入点表达式,该切入点表达式在调用findAll()方法之后执行。当我执行测试用例时,不会触发建议,而其他方法,例如findAll(Sort sort)findAll(Pageable pageable)也可以正常工作。我不确定这是否是Spring Boot或我的表达式的错误。我尝试使用Spring Boot 2.0.5和2.1.0,似乎没有什么可以解决我的问题

AddressLogging.java

@Aspect
@Configuration
public class AddressLogging {
    private Logger log=LoggerFactory.getLogger(AddressLogging.class);

    //@Pointcut("execution(* com.springtesting.repo.AddressRepository.*(..))")
    @Pointcut("execution(* com.springtesting.repo.AddressRepository.findAll())")
    public void getAddresses() {}

    @After("getAddresses()")
    public void afterAdvice() {
        log.error("Log Message: Inside afterAdvice() advice");
    }
}

AopTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class AopTest {
    @Autowired
    private AddressRepository addressRepository;

    @Test
    public void getAddresses() {
        //addressRepository.findAll(PageRequest.of(0,20, Sort.by("id")));
        addressRepository.findAll();
    }

    @Test
    public void findAddressById() {
        addressRepository.findById(1L);
    }
}

地址存储库

public interface AddressRepository extends JpaRepository<Address,Long> {}

1 个答案:

答案 0 :(得分:1)

Spring AOP方面也应为@Component,并通过组件扫描来获取。我不知道为什么将@Configuration添加到方面,因为这里没有配置。

也许您对单独的配置类的测试应该带有@Configuration批注,并且还应该激活@EnableAspectJAutoProxy(proxyTargetClass = true)@ComponentScan(basePackages = { "de.scrum_master" })之类的东西。

这是我的一个Spring AOP游乐场项目的摘录(我几乎不使用它,我不使用Spring AOP甚至不使用Spring本身,通常我使用功能更强大的AspectJ:

package de.scrum_master.app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = { "de.scrum_master" })
public class Application2 {
  public static void main(String[] args) throws Exception {
    ApplicationContext appContext = new AnnotationConfigApplicationContext(Application2.class);
    B b = (B) appContext.getBean("b");
    System.out.println(b.getData("bbb"));
    A a = (A) appContext.getBean("b");
    System.out.println(a.getData("aaa"));
  }
}