- public interface Animal {
- void yell();
- }
- @Service("tom")
- public class Cat implements Animal {
- public void yell(){
- System.out.println("Miao~,Miao~");
- }
- }
- @Component
- @Aspect
- public class Log {
- @Before("execution(* com.example.Cat.yell(..))")
- public void beforeDo() {
- System.out.println("before yell");
- }
- @After("execution(* com.example.Cat.yell(..))")
- public void afterDo() {
- System.out.println("after yell");
- }
- public void ex() {
- System.out.println("ex");
- }
- @Around("execution(* com.example.Cat.yell(..))")
- public void aroundDo(ProceedingJoinPoint joinpoint) {
- Date t = new Date();
- try {
- joinpoint.proceed();
- } catch (Throwable throwable) {
- throwable.printStackTrace();
- }
- Date t1 = new Date();
- System.out.println(t1.getTime() - t.getTime());
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.3.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
- <context:component-scan base-package="com.example"></context:component-scan>
- <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
- </beans>
- @SpringBootApplication
- public class AopdemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(AopdemoApplication.class, args);
- ApplicationContext ctx=new ClassPathXmlApplicationContext("a.xml");
- ((Animal)ctx.getBean("tom")).yell();
- }
- }
来源: https://www.oschina.net/code/snippet_1419328_58533