接口实现方式

步骤:

一、定义日志切面实现aop接口



package com.alec.aop.aspect;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
/**
* @author alce
*/
public class Log implements MethodBeforeAdvice, AfterReturningAdvice {

@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(method.getName()+"后置操作");
}

@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(method.getName()+"前置操作");
}
}


 二、定义需要切入的关注对象

由于spring采用动态代理的方式生成切面对象,需定义接口

接口:

    



package com.alec.aop.service;

/**
* @author alec
*/
public interface UserService {
/**
* 添加用户数据
*/
public void add() ;

/**
* 更新用户数据
*/
public void update();
}


实现类:

 



package com.alec.aop.service;

/**
* @author alec
*/
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("添加数据业务操作");
}

@Override
public void update() {
System.out.println("更新数据业务操作");
}
}


xml中配置信息:



<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注入Bean-->
<bean id="userService" class="com.alec.aop.service.UserServiceImpl"/>
<bean id="log" class="com.alec.aop.aspect.Log" />
<!--根据AOP接口,配置-->
<aop:config>
<!--定义切入点 需要切入的对象 UserServiceImpl下的所有方法都可以作为切入点-->
<aop:pointcut id="pointCut" expression="execution(* com.alec.aop.service.UserServiceImpl.*(..))"/>
<!--配置连接点,指定切面的方法-->
<aop:advisor advice-ref="log" pointcut-ref="pointCut"/>
</aop:config>
</beans>


验证:

  



package com.alec.aop;

import com.alec.aop.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @author alec
*/
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}