您的位置:首页 > 编程语言 > Java开发

Spring的AOP的总结

2019-03-09 16:09 120 查看

SpringAOP

SpringAOP:面向切面编程,常见应用场景有权限、事务、控制、日志等。
SpringAOP的原理:使用cglib代理设计模式。

用注解来模拟一下Spring的AOP

1、创建一个切面类=

/**
* 定义一个切面类
* @author 紫炎易霄
*/
@Component
@Aspect
public class TranAop {
@Before("execution(* com.zyyx.service.UserService.*(..))")
public void before(){
System.out.println("前置通知!");
}
@After("execution(* com.zyyx.service.UserService.*(..))")
public void after(){
System.out.println("后置通知!");
}
@AfterThrowing("execution(* com.zyyx.service.UserService.*(..))")
public void throwing(){
System.out.println("异常通知!");
}
@AfterReturning("execution(* com.zyyx.service.UserService.*(..))")
public void returning(){
System.out.println("返回通知!");
}
@Around("execution(* com.zyyx.service.UserService.*(..))")
public void arounding(ProceedingJoinPoint pJoinPoint) throws Throwable{
System.out.println("环绕通知的开头!");
pJoinPoint.proceed();
System.out.println("环绕通知的结尾!");

}
}

2、写一个dao和service

/**
* dao
* @author 紫炎易霄
*/
@Repository
public class UserDao {
public void work(){
System.out.println("我正在执行插入数据的操作!");
}
}
/**
* service
* @author 紫炎易霄
*/
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void work(){
userDao.work();
}
}

3、beans.xml文件的配置

<!-- 开启dao和service的扫描注解 -->
<context:component-scan base-package="com.zyyx"/>
<!-- 开启aop注解 -->
<aop:aspectj-autoproxy/>

4、、单元测试

public class TestSpringAop {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) ac.getBean("userService");
userService.work();
}
}

运行结果

用XML来模拟一下Spring的AOP

1、将切面类的注解清空

/**
* 定义一个切面类
* @author 紫炎易霄
*/
public class TranAop {
public void before(){
System.out.println("前置通知!");
}
public void after(){
System.out.println("后置通知!");
}
public void throwing(){
System.out.println("异常通知!");
}
public void returning(){
System.out.println("返回通知!");
}
public void arounding(ProceedingJoinPoint pJoinPoint) throws Throwable{
System.out.println("环绕通知的开头!");
pJoinPoint.proceed();
System.out.println("环绕通知的结尾!");
}
}

2、配置xml文件

<!-- 开启dao和service的扫描注解 -->
<context:component-scan base-package="com.zyyx"/>
<bean id="tranAop" class="com.zyyx.aop.TranAop" />
<!-- aop的配置 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut expression="execution(* com.zyyx.service.UserService.*(..))" id="point"/>
<!-- 切面 -->
<aop:aspect ref="tranAop">
<!-- 通知 -->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
<aop:after-throwing method="throwing" pointcut-ref="point"/>
<aop:around method="arounding" pointcut-ref="point"/>
<aop:after-returning method="returning" pointcut-ref="point"/>
</aop:aspect>
</aop:config>


运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: