AOP的配置
注解开发AOP制作步骤
在XML格式基础上
- 导入坐标(伴随spring-context坐标导入已经依赖导入完成)
- 开启AOP注解支持
- 配置切面@Aspect
- 定义专用的切入点方法,并配置切入点@Pointcut
- 为通知方法配置通知类型及对应切入点@Before
注解开发AOP注意事项
1.切入点最终体现为一个方法,无参无返回值,无实际方法体内容,但不能是抽象方法
2.引用切入点时必须使用方法调用名称,方法后面的()不能省略
3.切面类中定义的切入点只能在当前类中使用,如果想引用其他类中定义的切入点使用“类名.方法名()”引用
4.可以在通知类型注解后添加参数,实现XML配置中的属性,例如after-returning后的returning属性
AOP的注解驱动
AOP注解驱动
- 名称:@EnableAspectJAutoProxy
- 类型:注解
- 位置:Spring注解配置类定义上方
- 作用:设置当前类开启AOP注解驱动的支持,加载AOP注解
格式:
@Configuration @ComponentScan("com.limei") @EnableAspectJAutoProxy public class SpringConfig { }综合案例
首先 需要下载需要的sql:sql下载
案例目录结构
实体类和jdbc的编写
package com.limei.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/lianxi
jdbc.username=root
jdbc.password=123456config编写
package com.limei.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class JDBCConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
package com.limei.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.limei.domain");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.limei.dao");
return msc;
}
}
package com.limei.config;
import com.limei.aop.RunTimeMonitorAdvice;
import com.limei.config.JDBCConfig;
import com.limei.config.MyBatisConfig;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan ( "com" )
@PropertySource("classpath:jdbc.properties")
@Import({JDBCConfig.class, MyBatisConfig.class})
@EnableAspectJAutoProxy
public class SpringConfig {
}dao层编写
package com.limei.dao;
import com.limei.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface AccountDao {
@Insert("insert into account(name,money)values(#{name},#{money})")
void save(Account account);
@Delete("delete from account where id = #{id} ")
void delete(Integer id);
@Update("update account set name = #{name} , money = #{money} where id = #{id} ")
void update(Account account);
@Select("select * from account")
List<Account> findAll();
@Select("select * from account where id = #{id}")
Account findById(Integer id);
}service层编写
package com.limei.service;
import com.limei.domain.Account;
import java.util.List;
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
package com.limei.service.impl;
import com.limei.dao.AccountDao;
import com.limei.domain.Account;
import com.limei.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void save(Account account) {
accountDao.save(account);
}
public void update(Account account){
accountDao.update(account);
}
public void delete(Integer id) {
accountDao.delete(id);
}
public Account findById(Integer id) {
return accountDao.findById(id);
}
public List<Account> findAll() {
return accountDao.findAll();
}
}
aop的编写
package com.limei.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class RunTimeMonitorAdvice {
//切入点,监控业务层接口
@Pointcut("execution(* com.limei.service.*Service.find*(..))")
public void pt(){
}
@Around("pt()")
public Object runtimeAround(ProceedingJoinPoint pjp) throws Throwable {
//获取执行签名信息
Signature signature = pjp.getSignature();
//通过签名获取执行类型(接口名)
String className = signature.getDeclaringTypeName();
//通过签名获取执行操作名称(方法名)
String methodName = signature.getName();
//原始方法的调用
Object ret=pjp.proceed (pjp.getArgs ());
//执行时长累计值
long sum = 0L;
for (int i = 0; i < 10000; i++) {
//获取操作前系统时间beginTime
long startTime = System.currentTimeMillis();
//原始操作调用
pjp.proceed(pjp.getArgs());
//获取操作后系统时间endTime
long endTime = System.currentTimeMillis();
sum += endTime-startTime;
}
//打印信息
System.out.println(className+":"+methodName+" (万次)run:"+sum+"ms");
return ret;
}
}
测试类编写
package com.limei.service;
import com.limei.config.SpringConfig;
import com.limei.domain.Account;
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 java.util.List;
//设定spring专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class)
//设定加载的spring上下文对应的配置
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testFindById(){
Account ac = accountService.findById(1);
System.out.println(ac);
}
@Test
public void testFindAll(){
List<Account> list = accountService.findAll();
// System.out.println(list);
}
}
pom.xml
<?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.limei.aop</groupId>
<artifactId>Spring_aop</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
</project>
评论 (2)