程序员社区

使用Spring的API接口实现AOP

使用AOP,需要导入一个jar包:

 <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
	 <groupId>org.aspectj</groupId>
	 <artifactId>aspectjweaver</artifactId>
	 <version>1.9.4</version>
</dependency>

1.UserService接口:

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}

2.UserServiceImpl.java

public class UserServiceImpl implements UserService{

    public void add() {
        System.out.println("增加了一个用户");
    }
    public void delete() {
        System.out.println("删除一个用户");
    }
    public void update() {
        System.out.println("更新一个用户");
    }
    public void select() {
        System.out.println("查询一个用户");
    }
}

3.BeforeLog.java

public class BeforeLog implements MethodBeforeAdvice {
    //要执行的目标对象的方法(反射)
    //args:参数
    //target:目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

4.AfterLog.java

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
    }
}

5.ApplicationContext.xml

<!--配置AOP:需要导入AOP的约束-->
<aop:config>
    <!--切入点:expression:excution(要执行的位置 * * *)-->
    <aop:pointcut id="pointcut"
                  expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>

    <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>

在这里插入图片描述
6.MyTest.java

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        //动态代理代理的是接口
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 使用Spring的API接口实现AOP

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区