什么是AOP?
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP的第一个案例
要求:使用AOP实现日志记录功能,核心模块和增强单独开发,运行时组装
1.创建接口HelloDao、HelloService、
创建接口类HelloDaoImpl、HelloServiceImpl并实现dao层接口
public interface IHolleDao {
public void print();
}
public class IHolleDaoImpl implements IHolleDao {
public void print() {
System.out.println("数据写入成功");
}
}
public interface HolleService {
public void print();
}
public class HolleServiceImpl implements HolleService {
IHolleDao dao;
//封装属性
public IHolleDao getDao() {
return dao;
}
public void setDao(IHolleDao dao) {
this.dao = dao;
}
//重写print方法
public void print() {
dao.print();
}
}
2.创建前后置增强类
前置增强需实现MethodBeforeAdvice接口并实现before方法
后置增强需实现AfterReturningAdvice接口实现afterReturning方法
package cn.happy.day03aop.aop; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; /** * Created by Administrator on 2018/3/5. */ //前置增强 public class LoggerBefore implements MethodBeforeAdvice { public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println("记录日志"); } } ------------------------------------------------------------------ package cn.happy.day03aop.aop; import org.springframework.aop.AfterReturningAdvice; import java.lang.reflect.Method; /** * Created by Administrator on 2018/3/5. */ //后置增强 public class LoggerAfter implements AfterReturningAdvice { public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable { System.out.println("关闭"); } }
3.配置applicationContext.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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dao" class="cn.happy.day03aop.dao.IHolleDaoImpl">
</bean>
<bean id="service" class="cn.happy.day03aop.service.HolleServiceImpl">
<property name="dao" ref="dao"></property>
</bean>
<!--配置aop-->
<bean id="Before" class="cn.happy.day03aop.aop.LoggerBefore">
</bean>
<bean id="After" class="cn.happy.day03aop.aop.LoggerAfter">
</bean>
<aop:config>
<aop:pointcut id="mypoint" expression="execution(* *..service.*.*(..))"/>
<!--前置增强-->
<aop:advisor advice-ref="Before" pointcut-ref="mypoint"/>
<!--后置增强-->
<aop:advisor advice-ref="After" pointcut-ref="mypoint"/>
</aop:config>
</beans>
execution(【modifiers-pattern?】 访问修饰符
ret-type-pattern 返回值类型
【declaring-type-pattern?】 全限定性类名
name-pattern(param-pattern) 方法名(参数名) 包名.类型名.方法名
【throws-pattern?】) 抛出异常类型
【】内表示可以省略
*代表0或任意多个字符
..代表方法内任意多个参数
4.编写测试类
@Test
public void Spring(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext-day03aop.xml");
HolleService service=(HolleService)ctx.getBean("service");
service.print();
}
测试结果

分享完毕!