java–Spring 框架的 AOP
- Spring 框架的一个关键组件是面向方面的编程(AOP)框架。面向方面的编程需要把程序逻辑分解成不同的部分称为所谓的关注点。跨一个应用程序的多个点的功能被称为横切关注点,这些横切关注点在概念上独立于应用程序的业务逻辑。有各种各样的常见的很好的方面的例子,如日志记录、审计、声明式事务、安全性和缓存等。
- 在 OOP 中,关键单元模块度是类,而在 AOP 中单元模块度是方面。依赖注入帮助你对应用程序对象相互解耦和 AOP 可以帮助你从它们所影响的对象中对横切关注点解耦。AOP 是像编程语言的触发物,如 Perl,.NET,Java 或者其他。
- Spring AOP 模块提供拦截器来拦截一个应用程序,例如,当执行一个方法时,你可以在方法执行之前或之后添加额外的功能。
AOP 术语:
通知的类型:
基于 AOP 的 XML 架构:
实例(与上一篇代理相似,主要看xml文件配置):
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: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.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
">
<!--注入bean-->
<bean id="adminCheck" class="sc.impl.AdminCheck"></bean>
<bean id="transactionManager" class="sc.impl.TransactionManager"></bean>
<bean id="logManager" class="sc.impl.LogManager"></bean>
<bean id="bankDao" class="sc.impl.BankDaoImpl"></bean>
<!--<bean id="empDao" class="sc.impl.EmpDaoImpl"></bean>-->
<!--开始spring aop 面向切面-->
<aop:config>
<!--切入点-->
<aop:pointcut id="service" expression="execution(* sc.impl.*.*(..))"></aop:pointcut>
<aop:aspect id="adminInterceptor" ref="adminCheck">
<!--在此之前切入-->
<aop:before method="check" pointcut-ref="service"></aop:before>
</aop:aspect>
<aop:aspect id="transInterceptor" ref="transactionManager">
<aop:before method="begin" pointcut-ref="service"></aop:before>
</aop:aspect>
<aop:aspect id="logInterceptor" ref="logManager">
<aop:after method="writelog" pointcut-ref="service"></aop:after>
</aop:aspect>
<aop:aspect id="transInterceptor" ref="transactionManager">
<aop:after method="commit" pointcut-ref="service"></aop:after>
</aop:aspect>
</aop:config>
</beans>
测试:
package sc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sc.dao.BankDao;
import sc.impl.AdminCheck;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
BankDao bankDao = (BankDao) ac.getBean("bankDao");
AdminCheck adminCheck= (AdminCheck) ac.getBean("adminCheck");
// adminCheck.check();
System.out.println(bankDao.getClass().getName());
bankDao.remirt();
System.out.println("----------------------");
bankDao.save();
}
}
结果是:
运用AOP一样可以进行事务操作时切入事件,与java代理的作用相似,但我觉得AOP较为简单一点。