Spring-AOP-第一个简单的AOP项目

Spring-AOP-第一个简单的AOP项目

(1)导包

spring-context-5.2.8.RELEASE.jar

spring-expression-5.2.8.RELEASE.jar

spring-context-5.2.8.RELEASE-sources.jar

commons-logging-1.1.1.jar

spring-core-5.2.8.RELEASE.jar

spring-beans-5.2.8.RELEASE.jar

spring-aspects-5.2.8.RELEASE.jar

spring-aop-5.2.8.RELEASE.jar

 

(使用@Aspect注解需要导入)

com.springsource.org.aopalliance-1.0.0.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

com.springsource.net.sf.cglib-2.2.0.jar

 

(2)写配置

 ①将目标类和切面类(封装了通知方法(在目标方法执行前后执行的方法))加入IOC容器中(使用四个注解@Controller@Service@Component@Repository

②还要告诉Spring到底哪个是切面类?(使用@Aspect注解

③告诉Spring,切面类里面的每一个方法,都是何时何地运行?(使用切入点表达式

@Service
public class UserService {

    public void add()
    {
        System.out.println("UserService add...");
        System.out.println(1/0);
    }
}

 

@Component
@Aspect
public class UserServiceProxy {

    @After(value = "execution(* com.orz.spring.aop.UserService.add(..))")
    public void logAfter()
    {
        System.out.println("After");
    }

    @AfterReturning(value = "execution(* com.orz.spring.aop.UserService.add(..))")
    public void logAfterReturnning()
    {
        System.out.println("AfterReturnning");
    }
}

 

(3)开启基于注解的AOP模式

<context:component-scan base-package="com.orz.spring"/>
<aop:aspectj-autoproxy/>

(4)测试

@Test
public void test1()
{
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
    UserService userService = applicationContext.getBean("userService", UserService.class);
    userService.add();
}

(5)结果

UserService add...

After

 

java.lang.ArithmeticException: / by zero

  

 
posted @ 2020-10-23 09:24  orz江小鱼  阅读(283)  评论(0编辑  收藏  举报