Spring02-AOP
1,动态代理,指的是通过一个代理对象创建需要的业务对象,然后在这个代理对象中统一进行各种操作。
步骤:
1)写一个类实现InvocationHandler接口;
2)创建要代理的对象
2,创建一个简单的打印日志的类Logger
package com.yangw.spring.proxy;
import java.util.Date;
public class Logger {
public static void info(String msg){
System.out.println(new Date()+"----"+msg);
}
}
3,自定义注解类
package com.yangw.spring.model;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface LogInfo {
public String value() default "";
}
4,自定义动态代理类LogProxy
package com.yangw.spring.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.yangw.spring.model.LogInfo;
/**
* 1 写一个类,实现InvocationHandler接口
* @author Administrator
*
*/
public class LogProxy implements InvocationHandler {
//2,创建代理对象
private Object target;
private LogProxy(){};
//3,创建一个方法来生成代理对象,这个方法的参数是要代理的对象
public static Object getInstance(Object obj){
//3.1 创建LogProxy对象
LogProxy proxy=new LogProxy();
//3.2 设置代理对象
proxy.target=obj;
//3.3 通过Proxy.newProxyInstance()创建代理对象
//参数1:要代理对象的classloader,参数2:要代理对象的实现的所有接口,
//参数3:实现InvocationHandler接口的对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), proxy);
}
/**
* 当有了代理对象之后,都会调用下面的invoke()方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//这里怎么处理完全由我们来控制的
/*if(method.getName().equals("add")|| method.getName().equals("delete")){
Logger.info("调用我...");
}*/
//只对有LogInfo注解的进行处理,
//而且是在method.invoke调用之前,调用之后执行都可以
//在异常中进行处理也可以
if(method.isAnnotationPresent(LogInfo.class)){
Logger.info(method.getAnnotation(LogInfo.class).value());
}
return method.invoke(target, args);
//aspect orient program (面向切面编程)
}
}
5,在需要加入注解的接口上面加入自定义注解LogInfo
package com.yangw.spring.dao;
import com.yangw.spring.model.LogInfo;
import com.yangw.spring.model.User;
public interface IUserDao {
@LogInfo("add a user")
public void add(User user) ;
@LogInfo("delete a user")
public void delete(int id) ;
public User load(int id);
}
6,beans2.xml中的配置如下
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--1, 打开Spring的annotation -->
<context:annotation-config/>
<!-- 2, 设定Spring去那些包中找annotation -->
<context:component-scan base-package="com.yangw.spring" />
<!--用代理类实现
对于静态(static)的注入,使用factory-method
-->
<bean id="userDynamicDao" class="com.yangw.spring.proxy.LogProxy"
factory-method="getInstance">
<!--静态方法传入的参数 -->
<constructor-arg ref="userDao" />
</bean>
<!-- 依次加入想加入的
<bean id="msgDynamicDao" class="com.yangw.spring.proxy.LogProxy"
factory-method="getInstance">
<constructor-arg ref="MsgDao" />
</bean>
-->
</beans>
7,UserService类上注入userDynamicDao
package com.yangw.spring.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yangw.spring.dao.IUserDao;
import com.yangw.spring.model.User;
@Service("userService")
public class UserService implements IUserService {
@Resource(name="userDynamicDao")
private IUserDao userDao ;
@Override
public void add(User user) {
userDao.add(user);
}
@Override
public void delete(int id) {
userDao.delete(id);
}
@Override
public User load(int id) {
return userDao.load(id);
}
}
7, 测试
package com.yangw.spring.test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yangw.spring.action.UserAction;
import com.yangw.spring.model.User;
public class TestSpring {
//1,创建Spring工厂
BeanFactory factory= new ClassPathXmlApplicationContext("beans2.xml");
@Test
public void testUser(){
//2,通过工厂获取Spring的对象
UserAction userAction = factory.getBean("userAction", UserAction.class);
User u1=new User(1,"yangw");
userAction.setUser(u1);
userAction.add();
userAction.delete();
userAction.load();
}
}
8, Spring实现动态代理(基于annotation方式)
导入aopalliance-1.0.jar aspectjrt-1.6.10.jar aspectjweaver-1.7.2.jar 三个包,Spring使用这三个包实现AOP
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1, 打开Spring的annotation -->
<context:annotation-config/>
<!-- 2, 设定Spring去那些包中找annotation -->
<context:component-scan base-package="com.yangw.spring" />
<!-- 打开基于annotation的aop自动代理 -->
<aop:aspectj-autoproxy />
</beans>
切面类
package com.yangw.spring.proxy;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("logAspect") //交给Spring管理
@Aspect //说明是一个切面类
public class LogAspect {
//前置通知
// 第1个"*": 任意返回值
// 第2个"*": com.yangw.spring.dao包中的所有类
// 第3个"*": add*表示以add开头的所有方法
// "(..)" : 表示方法参数是任意值
// "||" : 可以用或表达式加入多个条件
/**
* 函数调用之前执行
*/
@Before("execution(* com.yangw.spring.dao.*.add*(..))||"
+"execution(* com.yangw.spring.dao.*.delete*(..))||"
+"execution(* com.yangw.spring.dao.*.update*(..))")
public void logStart(JoinPoint jp){
System.out.println(jp.getTarget()); //得到执行的类
System.out.println(jp.getSignature().getName()); //得到执行的方法名
Logger.info("log start.");
}
/**
* 函数调用之后执行
*/
@After("execution(* com.yangw.spring.dao.*.add*(..))||"
+"execution(* com.yangw.spring.dao.*.delete*(..))||"
+"execution(* com.yangw.spring.dao.*.update*(..))")
public void logEnd(JoinPoint jp){
System.out.println(jp.getTarget()); //得到执行的类
System.out.println(jp.getSignature().getName()); //得到执行的方法名
Logger.info("log end.");
}
/**
* 函数调用过程中执行
*/
@Around("execution(* com.yangw.spring.dao.*.add*(..))||"
+"execution(* com.yangw.spring.dao.*.delete*(..))||"
+"execution(* com.yangw.spring.dao.*.update*(..))")
public void logAround(ProceedingJoinPoint pjp) throws Throwable{
Logger.info("log around start");
pjp.proceed(); //让程序往下执行
Logger.info("log around end.");
}
}
测试
package com.yangw.spring.test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yangw.spring.action.UserAction;
import com.yangw.spring.model.User;
public class TestSpring {
//1,创建Spring工厂
BeanFactory factory= new ClassPathXmlApplicationContext("beans3.xml");
@Test
public void testUser(){
//2,通过工厂获取Spring的对象
UserAction userAction = factory.getBean("userAction", UserAction.class);
User u1=new User(1,"yangw");
userAction.setUser(u1);
userAction.add();
userAction.delete();
userAction.load();
}
}
测试结果
Mon Oct 21 19:13:29 CST 2013----log around start com.yangw.spring.dao.UserDao@18ce14a add Mon Oct 21 19:13:29 CST 2013----log start. add :User [id=1, username=yangw] Mon Oct 21 19:13:29 CST 2013----log around end. com.yangw.spring.dao.UserDao@18ce14a add Mon Oct 21 19:13:29 CST 2013----log end. Mon Oct 21 19:13:29 CST 2013----log around start com.yangw.spring.dao.UserDao@18ce14a delete Mon Oct 21 19:13:29 CST 2013----log start. delete :0 Mon Oct 21 19:13:29 CST 2013----log around end. com.yangw.spring.dao.UserDao@18ce14a delete Mon Oct 21 19:13:29 CST 2013----log end. load :0 null
9, Spring实现动态代理(基于xml方式) 一般这种用的多
导入aopalliance-1.0.jar aspectjrt-1.6.10.jar aspectjweaver-1.7.2.jar 三个包,Spring使用这三个包实现AOP
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1, 打开Spring的annotation -->
<context:annotation-config/>
<!-- 2, 设定Spring去那些包中找annotation -->
<context:component-scan base-package="com.yangw.spring" />
<aop:config>
<!-- 定义切面 -->
<aop:aspect id="myLogAspect" ref="logAspect">
<!-- 在哪些位置加入相应的Aspect-->
<aop:pointcut id="logPointCut" expression="execution(* com.yangw.spring.dao.*.add*(..))||
execution(* com.yangw.spring.dao.*.delete*(..))||
execution(* com.yangw.spring.dao.*.update*(..))" />
<!-- 定义通知 -->
<aop:before method="logStart" pointcut-ref="logPointCut"/>
<aop:after method="logEnd" pointcut-ref="logPointCut"/>
<aop:around method="logAround" pointcut-ref="logPointCut"/>
</aop:aspect>
</aop:config>
</beans>
package com.yangw.spring.proxy;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
@Component("logAspect") //交给Spring管理
public class LogAspect1 {
public void logStart(JoinPoint jp){
System.out.println(jp.getTarget()); //得到执行的类
System.out.println(jp.getSignature().getName()); //得到执行的方法名
Logger.info("log start.");
}
public void logEnd(JoinPoint jp){
System.out.println(jp.getTarget()); //得到执行的类
System.out.println(jp.getSignature().getName()); //得到执行的方法名
Logger.info("log end.");
}
public void logAround(ProceedingJoinPoint pjp) throws Throwable{
Logger.info("log around start");
pjp.proceed(); //让程序往下执行
Logger.info("log around end.");
}
}
测试和结果与前面的基于annotation的一模一样,不在赘述!
Spring02-AOP的更多相关文章
- JAVAEE——spring02:使用注解配置spring、sts插件、junit整合测试和aop演示
一.使用注解配置spring 1.步骤 1.1 导包4+2+spring-aop 1.2 为主配置文件引入新的命名空间(约束) 1.3 开启使用注解代替配置文件 1.4 在类中使用注解完成配置 2.将 ...
- Spring第二天——IOC注解操作与AOP概念
大致内容 spring的bean管理(注解实现) AOP原理 log4j介绍 spring整合web项目的演示 一.spring注解实现bean管理 注解: 代码中一些特殊的标记,使用注解也可以完成一 ...
- spring-02
spring-02 1.谈谈你对 Spring 的理解 Spring 是一个开源框架,为简化企业级应用开发而生.Spring 可以是使简单的 JavaBean 实现以前只有 EJB 才能实现的功能.S ...
- Spring03——有关于 Spring AOP 的总结
本文将为各位带来 Spring 的另一个重点知识点 -- Spring AOP.关注我的公众号「Java面典」,每天 10:24 和你一起了解更多 Java 相关知识点. 什么是 AOP 面向切面编程 ...
- 基于spring注解AOP的异常处理
一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...
- Spring基于AOP的事务管理
Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...
- 学习AOP之透过Spring的Ioc理解Advisor
花了几天时间来学习Spring,突然明白一个问题,就是看书不能让人理解Spring,一方面要结合使用场景,另一方面要阅读源代码,这种方式理解起来事半功倍.那看书有什么用呢?主要还是扩展视野,毕竟书是别 ...
- 学习AOP之深入一点Spring Aop
上一篇<学习AOP之认识一下SpringAOP>中大体的了解了代理.动态代理及SpringAop的知识.因为写的篇幅长了点所以还是再写一篇吧.接下来开始深入一点Spring aop的一些实 ...
- 学习AOP之认识一下Spring AOP
心碎之事 要说知道AOP这个词倒是很久很久以前了,但是直到今天我也不敢说非常的理解它,其中的各种概念即抽象又太拗口. 在几次面试中都被问及AOP,但是真的没有答上来,或者都在面上,这给面试官的感觉就是 ...
- .Net中的AOP系列之构建一个汽车租赁应用
返回<.Net中的AOP>系列学习总目录 本篇目录 开始一个新项目 没有AOP的生活 变更的代价 使用AOP重构 本系列的源码本人已托管于Coding上:点击查看. 本系列的实验环境:VS ...
随机推荐
- fedora23安装配置记录
一.安装fedora 1.下载fedora的镜像文件,个人比较喜欢gnome,因而直接下载工作站版本了! http://start.fedoraproject.org/这个是浏览器首页,提供了fedo ...
- c#Reverse字符串
class Program { static void Main(string[] args) { // 输出 ypoc si yek eht string str = "the key i ...
- 【Hadoop】 2.7.3版本 hdfs 命令行使用
1.查看HDFS下目录结构及文件 dream361@ubuntu:~$ hdfs dfs -ls -R / 2.创建文件目录/tmp dream361@ubuntu:~$ hdfs dfs -mkdi ...
- c++-STL:删除子串
void deletesub(string &str,const string &sub,int n) { int m,flag=0,num=0; //num是子串出现的次数 whil ...
- 短视频服务大PK,阿里云、腾讯云、又拍云、七牛云、金山云5强横向对比
继直播后,短视频又再次爆发,在这个风口,国内的各大云厂商也都相继推出了自己的一站式短视频解决方案.上周由于公司短视频功能开发的需要,对比了阿里云.腾讯云.又拍云.七牛云.金山云5家的短视频服务. 先介 ...
- css基础:格式与布局
1.定位:position:fixed:锁定位置,相当于屏幕位置锁定,不随页面移动. position:absolute:绝对位置,相对于页面定位,随页面移动. position:relative:相 ...
- mysql 插入字段 字符串
update hand_over set pay_info='{"waring_tip":"{\"pay_order_cancel\":0,\&qu ...
- 公司python入职培训流程
时间分为4周,全部自学,仅提供大纲.适用于Web方向:1.Week1:读完<简明Python教程>,适应Python开发环境2.Week2:写个爬虫,需要深入了解re.urllib2.s ...
- Day4 - Linux分区规划与xshell使用排错
1.1 没有重要数据 /boot 200M 存放系统的引导信息 内核 swap 交换分区 防止内存用光了 临时的一个内存 如果你的内存小于8G swap是内存的1.5倍 如果你的 ...
- 深入理解 JavaScript 中的 replace 方法(转)
replace方法是属于String对象的,可用于替换字符串. 简单介绍: StringObject.replace(searchValue,replaceValue) StringObject:字符 ...