我想在服务中运行获取消息方法之前运行切面。我不想使用xml配置,所以我添加了(希望)必要的注释。但是,当我运行我的应用程序时,切面不起作用,什么也没有发生。您能解释一下为什么吗?
服务
public interface Service {
void getMessage();
}
服务实现
import org.springframework.stereotype.Component;
@Service
public class ServiceImpl implements Service {
public void getMessage() {
System.out.println("Hello world");
}
}
方面
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class LoggingAspect {
@Before("execution(* com.example.aop.Service.getMessage())")
public void logBefore(JoinPoint joinPoint) {
System.out.println("AOP is working!!!");
}
}
运行
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan("com.example")
public class AopApplication {
public static void main(String[] args) {
final ConfigurableApplicationContext run = SpringApplication.run(AopApplication.class, args);
final Service bean = run.getBean(ServiceImpl.class);
bean.getMessage();
}
}
输出
仅为Hello world
getBean(Service.class)
。 - M. Prokhorov@Before("execution(* com.example.aop.ServiceImpl.getMessage())")
吗?请参见此处 https://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/。 - best wishes