欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSH与SSM学习之Spring16——Spring中AOP之使用配置文件配置

程序员文章站 2022-05-24 23:47:16
...

SSH与SSM学习之Spring16——Spring中AOP之使用配置文件配置

一、说明

Spring中使用AOP主要就是配置目标类,通知类,和织入。代理类如何创建之类的不用我们关心,因为Spring已经弄好了。

下面我们来看一下我们搞一把。


二、导包

除了之前使用的包外,下载还需要导入一下包。

  1. 导入 Spring 的aop包
spring-aop-4.3.9.RELEASE.jar
spring-aspects-4.3.9.RELEASE.jar
  1. 导入 Spring 需要的第三方 aop 包
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

三、创建目标类

这个目标类我们创建了一个接口和一个实现类。

3.1 UserService 接口

package com.qwm.spring2.service;
/**
 * @author:qiwenming
 * @date:2017/10/25 0025   23:08
 * @description:
 */
public interface UserService {
    void saveUser();
    void deleteUser();
    void updateUser();
    void findUser();
}

3.2 UserServiceImpl 目标类

package com.qwm.spring2.service;

/**
 * @author:qiwenming
 * @date:2017/10/25 0025   23:07
 * @description:
 */
public class UserServiceImpl implements UserService {
    @Override
    public void saveUser() {
        System.out.println("--保存用户--");
    }

    @Override
    public void deleteUser() {
        System.out.println("--删除用户--");
        //为了测试异常通知,弄出一异常
        int i = 1 / 0;
    }

    @Override
    public void updateUser() {
        System.out.println("--更新用户--");
    }

    @Override
    public void findUser() {
        System.out.println("--查找用户--");
    }
}

四、MyAdvice 通知类

package com.qwm.spring2.f_aopxml;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * @author:qiwenming
 * @date:2017/10/25 0025   23:10
 * @description:
 *  通知类
 */
public class MyAdvice {

    //前置通知
    //指定该方法是前置通知,并制定切入点
    public void before(){
        System.out.println("这是前置通知!!");
    }

    //后置通知
    public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }

    //环绕通知
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法
        System.out.println("这是环绕通知之后的部分!!");
        return proceed;
    }

    //异常通知
    public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }

    //后置通知
    public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}

五、applicationContext.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

    <!--1.配置目标对象-->
    <bean name="userService" class="com.qwm.spring2.service.UserServiceImpl"/>

    <!--2.配置通知-->
    <bean name="myAdvice" class="com.qwm.spring2.f_aopxml.MyAdvice"/>

    <!--3.织入-->
    <aop:config>
        <!--切入点-->
        <!--切入点配置说明

           切入点配置需要使用 execution()

                  下面这个是配置 UserServiceImpl的saveUser方法
           public void com.qwm.spring2.service.UserServiceImpl.saveUser()
                  public可以省略
           void com.qwm.spring2.service.UserServiceImpl.saveUser()
                  可以使用 * 表示指定返回值
           * com.qwm.spring2.service.UserServiceImpl.saveUser()
                  可以使用 * 表示配置所有方法
           * com.qwm.spring2.service.UserServiceImpl.*()

                 可以使用 * 表示匹配指定的类 (只会匹配 service包下的类)
            * com.qwm.spring2.service.*ServiceImpl.*()
                 可以使用 .. 表示匹配子包已经子子包(会匹配 service包下以及所有子包的类)
            * com.qwm.spring2.service..*ServiceImpl.*()
        -->
        <aop:pointcut id="pc" expression="execution(* com.qwm.spring2.service.*ServiceImpl.*())"/>
        <!--织入通知-->
        <aop:aspect ref="myAdvice">
            <!--前置通知-->
            <aop:before method="before" pointcut-ref="pc"/>
            <!--后置通知-->
            <aop:after-returning method="afterReturning" pointcut-ref="pc"/>
            <!--环绕通知-->
            <aop:around method="around" pointcut-ref="pc"/>
            <!--异常拦截通知-->
            <aop:after-throwing method="afterException" pointcut-ref="pc"/>
            <!--后置通知-->
            <aop:after method="after" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>

</beans>

六、AopXmlTest 测试

package com.qwm.spring2.f_aopxml;

import com.qwm.spring2.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;

/**
 * @author:qiwenming
 * @date:2017/10/25 0025   23:38
 * @description:
 * Aop xml 配置测试
 */
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:com/qwm/spring2/f_aopxml/applicationContext.xml")
public class AopXmlTest {

    @Resource(name = "userService")
    public UserService us;

    @Test
    public void test1(){
        us.saveUser();
    }

    @Test
    public void test2(){
        us.deleteUser();
    }
}

测试test1的结果是

这是前置通知!!
这是环绕通知之前的部分!!
--保存用户--
这是后置通知(出现异常也会调用)!!
这是环绕通知之后的部分!!
这是后置通知(如果出现异常不会调用)!!

测试test2的结果是

这是前置通知!!
这是环绕通知之前的部分!!
--删除用户--
这是后置通知(出现异常也会调用)!!
出事啦!出现异常了!!

java.lang.ArithmeticException: / by zero

    at com.qwm.spring2.service.UserServiceImpl.deleteUser(UserServiceImpl.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:47)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.qwm.spring2.f_aopxml.MyAdvice.around(MyAdvice.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy13.deleteUser(Unknown Source)
    at com.qwm.spring2.f_aopxml.AopXmlTest.test2(AopXmlTest.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

七、源码下载

https://github.com/wimingxxx/spring01/tree/master/src/com/qwm/spring2/f_aopxml