马士兵Spring-AOP-Aspect例子使用(1)
一、例子1:
1.工程结构:

2.
User.java:
package com.cy.model;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDAO.java:
package com.cy.dao;
import com.cy.model.User;
public interface UserDAO {
public void save(User user);
}
UserDAOImpl.java:
package com.cy.dao.impl; import org.springframework.stereotype.Component; import com.cy.dao.UserDAO;
import com.cy.model.User; @Component
public class UserDAOImpl implements UserDAO { public void save(User user) {
//Hibernate
//JDBC
//XML
//NetWork
System.out.println("user saved!");
//throw new RuntimeException("exeption!");
} }
UserService.java:
package com.cy.service; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.cy.dao.UserDAO;
import com.cy.model.User; @Component("userService")
public class UserService { @Resource
private UserDAO userDAO; public void init() {
System.out.println("init");
} public void add(User user) {
userDAO.save(user);
} public UserDAO getUserDAO() {
return userDAO;
} public void setUserDAO( UserDAO userDAO) {
this.userDAO = userDAO;
} public void destroy() {
System.out.println("destroy");
}
}
LogInterceptor.java:
package com.cy.aop; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogInterceptor { /**
* execution 专门的方法的切入语法;
* 可以很方便的指定加到哪个/哪些方法上;
* execution: 方法的执行;UserDAOImpl.save方法执行的时候;
* UserDAOImpl.save方法一执行,先把下面的方法before()加到前面 @Before
*/
@Before("execution(public void com.cy.dao.impl.UserDAOImpl.save(com.cy.model.User))")
public void before() {
System.out.println("method before");
}
}
beans.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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <context:annotation-config />
<context:component-scan base-package="com.cy"/> <!-- 在spring容器的初始化过程中,会将com.cy下面的所有类都会扫描,
扫描的时候发现@Component,将这个类初始化;
同时发现@Aspect,发现这是一个切面逻辑,可以把它切到其他类的方法上面去;
发现@Befored定义了下;在执行execution中的方法前面加入逻辑
-->
<aop:aspectj-autoproxy /> </beans>
测试代码:
UserServiceTest.java:
package com.cy.service; import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cy.model.User; public class UserServiceTest { @Test
public void testAdd() throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserService service = (UserService)ctx.getBean("userService");
System.out.println(service.getClass());
service.add(new User());
ctx.destroy();
}
}
运行结果:

一些概念:

二、例子2:
1.一些织入点语法:
1.the execution of any public method:
execution(public * *(..))
第1个* 任何返回值:
第2个* *(..)任何类的任何方法 2.the execution of any method with a name beginning with "set":
execution(* set*(..))
set*(..) 以set开头的任何方法 3.the execution of any method defined by the AccountService interface:
execution(* com.xyz.service.AccountService.*(..))
任何返回值;
com.xyz.service.AccountService类下面的任何方法; 4.the execution of any method defined in the service package:
execution(* com.xyz.service.*.*(..)) 5.the execution of any method defined in the service package or a sub-package:
execution(* com.xyz.service..*.*(..))
com.xyz.service下面的包,子包,不管子包多少层;里面的任何类任何方法; 6.any join point (method execution only in Spring AOP) within the service package:
within(com.xyz.service.*)
method execution only in Spring AOP spring自身也实现了一套AOP的语法;它也支持使用Aspect的语法来实现;
大部分情况下用不到spring自身的AOP;
2.各种各样类型的Advice:
1.Before advice 2.After returning advice
After returning advice runs when a matched method execution returns normally. It is declared using the @AfterReturning annotation:
只要这个方法正常执行完了,会执行我们的AfterReturning
如:
@AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doAccessCheck() {
// ...
} 3.After throwing advice
After throwing advice runs when a matched method execution exits by throwing an exception. It is declared using the @AfterThrowing annotation:
当一个方法执行抛出异常的时候,抛出了任何异常,就会执行@AfterThrowing
如:
@AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doRecoveryActions() {
// ...
} 4.After (finally) advice
执行你的方法时候是写try catch finally;catch到异常的时候是执行@AfterThrowing;最后一定会执行finally; 5.Around advice
around环绕;前面可以加逻辑,后面也可以加逻辑;
如:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
public class AroundExample { @Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch 加了自己的逻辑;
Object retVal = pjp.proceed(); //想让程序继续执行,必须调pjp.proceed(),程序才会继续运行;可以参考责任链设计模式;
//struts2的Interceptor也是这么用的;
// stop stopwatch 后面加自己的逻辑
return retVal;
}
}
使用例子1:
LogInterceptor.java:
package com.cy.aop; import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogInterceptor { /**
* execution 方法运行
* com.cy.dao下面包括它的子包下面,任何类的任何方法;返回值任何类型
*/
@Before("execution(public * com.cy.dao..*.*(..))")
public void before() {
System.out.println("method before");
} /**
* @AfterReturning 方法正常执行完成之后
*
*/
@AfterReturning("execution(public * com.cy.dao..*.*(..))")
public void afterReturning() {
System.out.println("method after returning");
} }
运行UserServiceTest.java:--- console:

使用例子2:afterThrowing:
LogInterceptor.java:
package com.cy.aop; import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogInterceptor { @Before("execution(public * com.cy.dao..*.*(..))")
public void before() {
System.out.println("method before");
} @AfterThrowing("execution(public * com.cy.dao..*.*(..))")
public void afterThrowing() {
System.out.println("method after throwing");
} }
UserDAOImpl.java中手动抛出一个异常:
@Component
public class UserDAOImpl implements UserDAO { public void save(User user) {
//Hibernate
//JDBC
//XML
//NetWork
System.out.println("user saved!");
throw new RuntimeException("exeption!");
} }
console:

使用例子3:@Around:
LogInterceptor.java:
package com.cy.aop; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogInterceptor { @Before("execution(public * com.cy.dao..*.*(..))")
public void before() {
System.out.println("method before");
} @Around("execution(public * com.cy.dao..*.*(..))")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
} }
console:

使用例子4:
把切点定义到UserService.java中的add方法上:
LogInterceptor.java:
package com.cy.aop; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogInterceptor { @Before("execution(public * com.cy.service..*.add(..))")
public void before() {
System.out.println("method before");
} @Around("execution(public * com.cy.dao..*.*(..))")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
} }
运行junit但是报错了:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [E:\jdbcWorkspace\spring_aop\bin\com\cy\service\UserService.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.


马士兵Spring-AOP-Aspect例子使用(1)的更多相关文章
- Spring aop 小例子demo
由于最近的服务项目提供接口有一个需求,所有操作都必须检查操作的服务可用,所以感觉Aop特别适合实施.完成学习的小例子. 关于spring-Aop原理:http://m.oschina.net/blog ...
- 马士兵 spring 视频笔记
课程内容 1. 面向接口(抽象)编程的概念与好处 2. IOC/DI的概念与好处 a) inversion of control b) dependen ...
- Spring AOP 学习例子
http://outofmemory.cn/code-snippet/3762/Spring-AOP-learn-example 工作忙,时间紧,不过事情再多,学习是必须的.记得以前的部门老大 ...
- Spring AOP @Aspect
spring提供了两个核心功能,一个是IoC(控制反转),另外一个便是Aop(面向切面编程),IoC有助于应用对象之间的解耦,AOP则可以实现横切关注点(如日志.安全.缓存和事务管理)与他们所影响的对 ...
- Spring AOP(aspect oriented programming) 转载
1.面向切面的基本原理 软件系统可以看成是由一组关注点组成的,其中,直接的业务关注点,是直切关注点.而为直切关注点提供服务的,就是横切关注点. 01.什么是面向切面编程 横切关注点:影响应用多处的功能 ...
- Spring AOP Aspect的简单实现(基于XML)
第一步:导包 第二步:实现类和切面类 Service("userService")public class IUserviceImpl implements IUserServic ...
- Spring AOP Aspect的简单实现(基于注解)
第1步:声明使用注解 <!-- 配置扫描注解--> 扫描包的位置<context:component-scan base-package="com.zz"/> ...
- Spring AOP实战例子与springmvc整合不起效果的解决办法
在使用AOP之前,首先我们先了解一下什么是AOP吧.在网上很多人将AOP翻译为“面向切面编程”,什么是面向切面?与面向对象有什么区别呢? 在回答这两个问题之前,我们先要明白切面的概念. 切面由切点与增 ...
- [Spring] AOP, Aspect实例解析
最近要用到切面来统一处理日志记录,写了个小实例练了练手: 具体实现类: public interface PersonServer { public void save(String name); p ...
- c# spring aop的简单例子
刚刚完成了一个c#的spring aop简单例子,是在mac下用Xamarin Studio开发的.代码如下: 接口 using System; using System.Collections.Ge ...
随机推荐
- HttpClient 4.5.3 get和post请求
HttpCilent 4.5.3 域名购买.com 后缀好域名 https://mi.aliyun.com/shop/38040 GET请求 CloseableHttpClient httpCilen ...
- scrapy中的canonicalize_url【转】
转自:http://www.leyle.com/archives/canonicalize_url.html 思考一下:对url进行规范化处理是否是必须的?因为这一步处理涉及到编码转换,对于一个网页的 ...
- Linux中重定向--转载
转:http://blog.csdn.net/songyang516/article/details/6758256 1重定向 1.1 重定向符号 > 输出 ...
- BooStrap4文档摘录: 1. Layout
文档: https://getbootstrap.com/docs/4.1/layout/overview/ w3c的案例:很直观: https://www.w3schools.com/bootst ...
- supervisor进程管理工具
Supervisor 一个python写的进程管理工具,用来启动.关闭.重启进程,可以同时控制多个进程. 安装: pip install supervisor 配置: 通过配置文件来满足自己的需求 配 ...
- 51nod-1420-贪心
1420 数袋鼠好有趣 题目来源: CodeForces 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题 收藏 关注 有n只袋鼠.每只袋鼠的大小用一个整数表示 ...
- 根据rowid查找所属的对象号、文件号、块号、行号-还是简单一点吧
select rowid, dbms_rowid.rowid_object(rowid) obj#, dbms_rowid.rowid_block_number(rowid) ...
- Access数据库 更新 "延时" 现象
最近发现 Access数据库执行Update或Delete操作成功后,执行select回来的数据未更改.打开数据库查看时却发现已更改,再次执行select 后却发现正常了. 经调试发现:Access数 ...
- poj3680
题解: 相邻的建边 每一段建边 然后见一个原点,汇点 代码: #include<cstdio> #include<cmath> #include<cstring> ...
- 爬虫框架:scrapy
一 介绍 Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速.简单.可扩展的方式从网站中提取所需的数据.但目前Scrapy的用途十分广泛,可 ...