2021-04-14

springAOP

代理模式

一、代理模式代理模式作为23种经典设计模式之一,其比较官方的定义为“为其他对象提供一种代理以控制对这个对象的访问”,简单点说就是,之前A类自己做一件事,在使用代理之后,A类不直接去做,而是由A类的代理类B来去做。代理类其实是在之前类的基础上做了一层封装。java中有静态代理、JDK动态代理、CGLib动态代理的方式。静态代理指的是代理类是在编译期就存在的,相反动态代理则是在程序运行期动态生成的,二、静态代理静态代理,简单点来说就是在程序运行之前,代理类和被代理类的关系已经确定。

简单转账功能

编写properties文件
jdbc.driverClass = com.mysql.jdbc.Driverjdbc.jdbcUrl = jdbc:mysql://localhost:3306/springjdbc.user = rootjdbc.password = 123456dao层编写package com.xf.dao;/** * @author xfgg /public interface AccountDao { / 汇款 / public void out(String outUser,int money); / 收款 / public void in(String inUser,int money);}package com.xf.dao.impl;import com.xf.dao.AccountDao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;/* * @author xfgg /public class AccountDaoImpl implements AccountDao { @Autowired private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate){ this.jdbcTemplate=jdbcTemplate; } @Override public void out(String outUser, int money) { this.jdbcTemplate.update(“update account set money =money-?” + “where username =?”,money,outUser); } @Override public void in(String inUser, int money) { this.jdbcTemplate.update(“update account set money =money+?” +“where username=?”,money,inUser); }}service层编写package com.xf.service;public interface AccountService { public void transfer(String outUser,String inUser,int money);}package com.xf.service.impl;import com.xf.dao.AccountDao;import com.xf.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; public void setAccountDao(AccountDao accountDao){ this.accountDao=accountDao; } @Override public void transfer(String outUser, String inUser, int money) { this.accountDao.out(outUser,money); this.accountDao.in(inUser,money); }}
编写application.xml配置文件<?xml version="1.0" encoding="UTF-8"?> <context:component-scan base-package=“com.xf.dao”/> <context:component-scan base-package=“com.xf.service”/> <context:property-placeholder location=“c3p0-db.properties”/> <tx:advice id=“txAdvice” transaction-manager=“txManager”> tx:attributes <tx:method name="find
" propagation=“SUPPORTS” rollback-for=“Exception”/> <tx:method name="" propagation=“REQUIRED” isolation=“DEFAULT” read-only=“false”/> </tx:attributes> </tx:advice> aop:config <aop:pointcut id=“txPointCut” expression="execution( com.xf.service..(…))"/> <aop:advisor advice-ref=“txAdvice” pointcut-ref=“txPointCut”/> </aop:config>
编写Test方法
package com.xf.test;import com.xf.service.AccountService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author xfgg */public class AccountTest { @Test public void test(){ String xmlPath = “applicationContext.xml”; ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath); AccountService accountService = (AccountService) applicationContext.getBean(“accountService”); accountService.transfer(“aaa”,“bbb”,100); }}使用注解方式进行事务管理修改application.xml配置文件 <?xml version="1.0" encoding="UTF-8"?> <context:property-placeholder location=“classpath:c3p0-db.properties” /> <tx:annotation-driven transaction-manager=“txManager”/> 修改AccountServiceImpl方法 package com.mengma.service.impl; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.mengma.dao.AccountDao; @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false) public class AccountServiceImpl { private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } public void transfer(String outUser, String inUser, int money) { this.accountDao.out(outUser, money); // 模拟断电 int i = 1 / 0; this.accountDao.in(inUser, money); } }

引入代理模式解决事务

package cn.com.staticProxy;/** * *

Title: IUserDao

Description:公共的接口

*

Company:

* @author Administrator* @date 2019年4月24日 下午4:15:12 /public interface IUserDao { void save(); void find();}然后是代理类和被代理类,先看被代理类,package cn.com.staticProxy;public class UserDao implements IUserDao{/* * 被代理类或者叫代理目标类 / @Override public void save() { // TODO Auto-generated method stub System.out.println(“模拟保存用户”); } @Override public void find() { // TODO Auto-generated method stub System.out.println(“模拟查找用户”); }}从被代理类上可以看到,被代理类要做的就是save和find操作,如果不使用代理模式,那么我们的使用方式则是直接使用,如下package cn.com.staticProxy;/* * *

Title: Test2

Description:直接使用被代理类

*

Company:

* @author Administrator* @date 2019年4月24日 下午4:18:39 /public class Test2 { public static void main(String[] args) { // TODO Auto-generated method stub IUserDao udp=new UserDao(); udp.save(); System.out.println("-------------------"); udp.find(); }}通过测试方法,可以得出执行方法的结果如下,模拟保存用户-------------------模拟查找用户 下面看代理类,package cn.com.staticProxy;public class UserDaoProxy implements IUserDao { private UserDao ud = new UserDao(); @Override public void save() { // TODO Auto-generated method stub System.out.println(“代理操作,开启事务”); ud.save(); System.out.println(“代理操作,关闭事务”); } @Override public void find() { // TODO Auto-generated method stub System.out.println(“代理操作,开启事务”); ud.find(); System.out.println(“代理操作,关闭事务”); }}可以看到代理类的实现逻辑是在代理类中持有一个被代理类的实例,通过被代理类实例调用被代理对象的方法,另外在方法之前前后均可加入其它的方法处理逻辑,最后,看使用代理类的测试方法,package cn.com.staticProxy;public class Test { public static void main(String[] args) { // TODO Auto-generated method stub IUserDao udp=new UserDaoProxy(); udp.save(); System.out.println("-------------------"); udp.find(); }}返回的执行结果如下,代理操作,开启事务模拟保存用户代理操作,关闭事务-------------------代理操作,开启事务模拟查找用户代理操作,关闭事务对比,使用静态代理和不使用静态代理,可以发现使用了代理之后,可以在被代理方法的执行前或后加入别的代码,实现诸如权限及日志的操作引入AOPAOP采取横向抽取机制,将分散在各个方法中的重复代码提取出来,然后在程序编译或运行时,再将这些提取出来的代码应用到需要执行的地方。这种采用横向抽取机制的方式,采用传统的OOP思想显然是无法办到的,因为OOP只能实现父子关系的纵向的重用。虽然AOP是一种新的编程思想,但却不是OOP的替代品,它只是OOP的延伸和补充。定义接口package com.abc.service;public interface ISomeService { public void first(); public void second(); }实现类package com.abc.service;public class SomeServiceImpl implements ISomeService {public void first() {System.out.println(“1”);}public void second() {System.out.println(“2”);}}代理类测试package com.abc.test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import com.abc.service.ISomeService;import com.abc.service.SomeServiceImpl;public class MyTest {public static void main(String[] args){ ISomeService target =new SomeServiceImpl(); ISomeService service =( ISomeService )Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(target, args);return result; } }); service.first(); service.second(); }} XML改注解(AOP)XML配置AOPpublic class Test { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“beans.xml”); UserService userService = (UserService) applicationContext.getBean(“userServiceImpl”); userService.hello(“cj”); }}public class Aspect1 { public void before() { System.out.println(“Before”); } public void afterReturning() { System.out.println(“AfterReturning”); }代理模式
一、代理模式代理模式作为23种经典设计模式之一,其比较官方的定义为“为其他对象提供一种代理以控制对这个对象的访问”,简单点说就是,之前A类自己做一件事,在使用代理之后,A类不直接去做,而是由A类的代理类B来去做。代理类其实是在之前类的基础上做了一层封装。java中有静态代理、JDK动态代理、CGLib动态代理的方式。静态代理指的是代理类是在编译期就存在的,相反动态代理则是在程序运行期动态生成的,二、静态代理静态代理,简单点来说就是在程序运行之前,代理类和被代理类的关系已经确定。简单转账功能编写properties文件jdbc.driverClass = com.mysql.jdbc.Driverjdbc.jdbcUrl = jdbc:mysql://localhost:3306/springjdbc.user = rootjdbc.password = 123456dao层编写package com.xf.dao;/
* * @author xfgg /public interface AccountDao { / 汇款 / public void out(String outUser,int money); / 收款 / public void in(String inUser,int money);}package com.xf.dao.impl;import com.xf.dao.AccountDao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;/* * @author xfgg /public class AccountDaoImpl implements AccountDao { @Autowired private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate){ this.jdbcTemplate=jdbcTemplate; } @Override public void out(String outUser, int money) { this.jdbcTemplate.update(“update account set money =money-?” + “where username =?”,money,outUser); } @Override public void in(String inUser, int money) { this.jdbcTemplate.update(“update account set money =money+?” +“where username=?”,money,inUser); }}service层编写package com.xf.service;public interface AccountService { public void transfer(String outUser,String inUser,int money);}package com.xf.service.impl;import com.xf.dao.AccountDao;import com.xf.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; public void setAccountDao(AccountDao accountDao){ this.accountDao=accountDao; } @Override public void transfer(String outUser, String inUser, int money) { this.accountDao.out(outUser,money); this.accountDao.in(inUser,money); }}编写application.xml配置文件<?xml version="1.0" encoding="UTF-8"?> <context:component-scan base-package=“com.xf.dao”/> <context:component-scan base-package=“com.xf.service”/> <context:property-placeholder location=“c3p0-db.properties”/> <tx:advice id=“txAdvice” transaction-manager=“txManager”> tx:attributes <tx:method name="find" propagation=“SUPPORTS” rollback-for=“Exception”/> <tx:method name=" " propagation=“REQUIRED” isolation=“DEFAULT” read-only=“false”/> </tx:attributes> </tx:advice> aop:config <aop:pointcut id=“txPointCut” expression="execution( com.xf.service. .(…))"/> <aop:advisor advice-ref=“txAdvice” pointcut-ref=“txPointCut”/> </aop:config>编写Test方法package com.xf.test;import com.xf.service.AccountService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author xfgg /public class AccountTest { @Test public void test(){ String xmlPath = “applicationContext.xml”; ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath); AccountService accountService = (AccountService) applicationContext.getBean(“accountService”); accountService.transfer(“aaa”,“bbb”,100); }}使用注解方式进行事务管理修改application.xml配置文件 <?xml version="1.0" encoding="UTF-8"?> <context:property-placeholder location=“classpath:c3p0-db.properties” /> <tx:annotation-driven transaction-manager=“txManager”/> 修改AccountServiceImpl方法 package com.mengma.service.impl; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.mengma.dao.AccountDao; @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false) public class AccountServiceImpl { private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } public void transfer(String outUser, String inUser, int money) { this.accountDao.out(outUser, money); // 模拟断电 int i = 1 / 0; this.accountDao.in(inUser, money); } }引入代理模式解决事务package cn.com.staticProxy;/* * *

Title: IUserDao

Description:公共的接口

*

Company:

* @author Administrator* @date 2019年4月24日 下午4:15:12 /public interface IUserDao { void save(); void find();}然后是代理类和被代理类,先看被代理类,package cn.com.staticProxy;public class UserDao implements IUserDao{/* * 被代理类或者叫代理目标类 / @Override public void save() { // TODO Auto-generated method stub System.out.println(“模拟保存用户”); } @Override public void find() { // TODO Auto-generated method stub System.out.println(“模拟查找用户”); }}从被代理类上可以看到,被代理类要做的就是save和find操作,如果不使用代理模式,那么我们的使用方式则是直接使用,如下package cn.com.staticProxy;/* * *

Title: Test2

Description:直接使用被代理类

*

Company:

* @author Administrator* @date 2019年4月24日 下午4:18:39 */public class Test2 { public static void main(String[] args) { // TODO Auto-generated method stub IUserDao udp=new UserDao(); udp.save(); System.out.println("-------------------"); udp.find(); }}通过测试方法,可以得出执行方法的结果如下,模拟保存用户-------------------模拟查找用户 下面看代理类,package cn.com.staticProxy;public class UserDaoProxy implements IUserDao { private UserDao ud = new UserDao(); @Override public void save() { // TODO Auto-generated method stub System.out.println(“代理操作,开启事务”); ud.save(); System.out.println(“代理操作,关闭事务”); } @Override public void find() { // TODO Auto-generated method stub System.out.println(“代理操作,开启事务”); ud.find(); System.out.println(“代理操作,关闭事务”); }}可以看到代理类的实现逻辑是在代理类中持有一个被代理类的实例,通过被代理类实例调用被代理对象的方法,另外在方法之前前后均可加入其它的方法处理逻辑,最后,看使用代理类的测试方法,package cn.com.staticProxy;public class Test { public static void main(String[] args) { // TODO Auto-generated method stub IUserDao udp=new UserDaoProxy(); udp.save(); System.out.println("-------------------"); udp.find(); }}返回的执行结果如下,代理操作,开启事务模拟保存用户代理操作,关闭事务-------------------代理操作,开启事务模拟查找用户代理操作,关闭事务对比,使用静态代理和不使用静态代理,可以发现使用了代理之后,可以在被代理方法的执行前或后加入别的代码,实现诸如权限及日志的操作

引入AOP

AOP采取横向抽取机制,将分散在各个方法中的重复代码提取出来,然后在程序编译或运行时,再将这些提取出来的代码应用到需要执行的地方。这种采用横向抽取机制的方式,采用传统的OOP思想显然是无法办到的,因为OOP只能实现父子关系的纵向的重用。虽然AOP是一种新的编程思想,但却不是OOP的替代品,它只是OOP的延伸和补充。定义接口package com.abc.service;public interface ISomeService { public void first(); public void second(); }实现类package com.abc.service;public class SomeServiceImpl implements ISomeService {public void first() {System.out.println(“1”);}public void second() {System.out.println(“2”);}}代理类测试package com.abc.test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import com.abc.service.ISomeService;import com.abc.service.SomeServiceImpl;public class MyTest {public static void main(String[] args){ ISomeService target =new SomeServiceImpl(); ISomeService service =( ISomeService )Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(target, args);return result; } }); service.first(); service.second(); }}

XML改注解(AOP)

XML配置AOPpublic class Test { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“beans.xml”); UserService userService = (UserService) applicationContext.getBean(“userServiceImpl”); userService.hello(“cj”); }}public class Aspect1 { public void before() { System.out.println(“Before”); } public void afterReturning() { System.out.println(“AfterReturning”); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值