Java55spring:AOP
Posted 码农编程录
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java55spring:AOP相关的知识,希望对你有一定的参考价值。
1.转账业务
1.1 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>spring_day03_01</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
</project>
//applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driverClass}"></property>
</bean>
<bean id="factoryBean" class="com.itheima.utils.ProxyBeanFactory">
<property name="accountService" ref="accountService"></property>
</bean>
<bean id="proxyAccountService" factory-bean="factoryBean" factory-method="getAccountServiceProxyObject"></bean>
</beans>
//jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/spring_day02
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
1.2 service
package com.itheima.service;
public interface AccountService {
public void transfer(String outName,String inName,double money);
public void update();
public void delete();
}
package com.itheima.service.impl;
import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void update() {
System.out.println("更新");
}
@Override
public void delete() {
System.out.println("删除");
}
@Override
public void transfer(String outName, String inName, double money) {
//对update,delete,transfer三个方法都加上事务,用动态代理对AccountServiceImpl进行增强
//创建AccountServiceImpl对象的代理对象, 我们调用这些update方法执行代理对象的方法。
//动态代理方式没有impl实现类,怎么装到spring容器中?以前不管是注解还是bean标签都要求有实现类
//装配对象即创建对象的三种方式
// try {
// System.out.println("开启事务");
//1.查询付款人的账户信息
Account outAccount = accountDao.findAccountByName(outName);
//2.查询收款人的账户信息
Account inAccount = accountDao.findAccountByName(inName);
//对2人的账户进行添加和减少的操作
outAccount.setMoney(outAccount.getMoney()-money);
inAccount.setMoney(inAccount.getMoney()+money);
//3.将更新后的账户信息更新到数据库
accountDao.update(outAccount);
int i = 1/0;
accountDao.update(inAccount);
// System.out.println("提交事务");
// } catch (Exception e) {
// System.out.println("回滚事务");
// e.printStackTrace();
// }
}
}
1.3 dao
package com.itheima.dao;
import com.itheima.domain.Account;
public interface AccountDao {
public Account findAccountByName(String name);
public void update(Account account);
}
package com.itheima.dao.impl;
import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate ;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountByName(String name) {
String sql = "select * from account where name = ?";
Account account = null;
try {
account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), name);
} catch (DataAccessException e) {
e.printStackTrace();
}
return account;
}
@Override
public void update(Account account) {
String sql = "update account set money = ? where name = ?";
jdbcTemplate.update(sql,account.getMoney(),account.getName());
}
}
1.4 test
package com.itheima.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
@Resource(name = "proxyAccountService")
private AccountService accountService;
@Test
public void transfer() {
String outName = "aaa";
String inName ="bbb";
double money = 500;
accountService.transfer(outName,inName,money);
}
@Test
public void update(){
accountService.update();
}
@Test
public void delete(){
accountService.delete();
}
}
transfer执行结果如下:
2.jdk动态代理原理
package com.itheima.proxy;
public interface IActor {
public void sing();
public void active();
}
package com.itheima.proxy;
public class ActorImpl implements IActor {
@Override
public void sing() {
System.out.println("唱歌");
}
@Override
public void active() {
System.out.println("表演");
}
}
动态代理:不修改源码情况下,对现有方法进行增强,要增强的功能只要写一遍就可以了。
package com.itheima.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkProxyTest {
public static void main(String[] args) {
IActor actor = new ActorImpl(); //需要创建一个对象来代理需要增强的actor对象
/**
* 参数1:类加载器,一般写被代理对象的类加载器
* 参数2:接口,被代理对象实现的接口。
* 参数3:处理器
*/
IActor iActor = (IActor) Proxy.newProxyInstance(actor.getClass().getClassLoader(), actor.getClass().getInterfaces(),
new InvocationHandler() { //选中方法名,按ctrl+q查看方法注释
/**
* @param proxy 被代理对象本身。没用。
* @param method 被调用的方法。
* @param args 调用方法时传递的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("增强的功能");
/**
* 参数1:方法调用时依赖的对象
* 参数2:调用方法时需要传递的参数
*/
return method.invoke(actor,args); //调用原有方法的功能
}
});
iActor.sing();
iActor.active();
// IActor actor2 = new $Proxy0();
// actor2.sing();
// actor2.active();
}
}
3.cglib动态代理
jdk动态代理产生iActor对象必须要有接口IActor,但很多时候我们要增强的对象ActorImpl没有接口IActor ,用cglib动态代理。
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
package com.itheima.proxy;
public class Actor2 {
public void dance(){
System.out.println("跳舞");
}
}
package com.itheima.proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf阿里四面:你知道Spring AOP创建Proxy的过程吗?