🍓系列专栏:Spring系列专栏
🍉个人主页:个人主页
- "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.0modelVersion>
-
- <groupId>com.itheimagroupId>
- <artifactId>spring_21_case_interface_run_speedartifactId>
- <version>1.0-SNAPSHOTversion>
-
- <dependencies>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>5.2.10.RELEASEversion>
- dependency>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-jdbcartifactId>
- <version>5.2.10.RELEASEversion>
- dependency>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-testartifactId>
- <version>5.2.10.RELEASEversion>
- dependency>
-
- <dependency>
- <groupId>org.aspectjgroupId>
- <artifactId>aspectjweaverartifactId>
- <version>1.9.4version>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.47version>
- dependency>
-
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druidartifactId>
- <version>1.1.16version>
- dependency>
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>3.5.6version>
- dependency>
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>1.3.0version>
- dependency>
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.12version>
- <scope>testscope>
- dependency>
- dependencies>
- project>
- public interface AccountService {
-
- void save(Account account);
-
- void delete(Integer id);
-
- void update(Account account);
-
- List
findAll(); -
- Account findById(Integer id);
-
- }
- @Service
- 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
findAll() { - return accountDao.findAll();
- }
- }
- public interface AccountDao {
-
- @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
- void save(Account account);
-
- @Delete("delete from tbl_account where id = #{id} ")
- void delete(Integer id);
-
- @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
- void update(Account account);
-
- @Select("select * from tbl_account")
- List
findAll(); -
- @Select("select * from tbl_account where id = #{id} ")
- Account findById(Integer id);
- }
- 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/spring_db?useSSL=false
- jdbc.username=root
- jdbc.password=root
- @Configuration
- @ComponentScan("com.itheima")
- @PropertySource("classpath:jdbc.properties")
- @Import({JdbcConfig.class,MybatisConfig.class})
-
- public class SpringConfig {
- }
- 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
- public DataSource dataSource(){
- DruidDataSource ds = new DruidDataSource();
- ds.setDriverClassName(driver);
- ds.setUrl(url);
- ds.setUsername(userName);
- ds.setPassword(password);
- return ds;
- }
- }
- public class MybatisConfig {
-
- @Bean
- public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
- SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
- ssfb.setTypeAliasesPackage("com.itheima.domain");
- ssfb.setDataSource(dataSource);
- return ssfb;
- }
-
- @Bean
- public MapperScannerConfigurer mapperScannerConfigurer(){
- MapperScannerConfigurer msc = new MapperScannerConfigurer();
- msc.setBasePackage("com.itheima.dao");
- return msc;
- }
- }
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(classes = SpringConfig.class)
- public class AccountServiceTestCase {
- @Autowired
- private AccountService accountService;
-
- @Test
- public void testFindById(){
- Account ac = accountService.findById(2);
- }
-
- @Test
- public void testFindAll(){
- List
all = accountService.findAll(); - }
-
- }
@EnableAspectJAutoProxy
- @Component
- @Aspect
- public class ProjectAdvice {
- //匹配业务层的所有方法
- @Pointcut("execution(* com.itheima.service.*Service.*(..))")
- private void servicePt(){}
-
-
- }
- @Component
- @Aspect
- public class ProjectAdvice {
- //匹配业务层的所有方法
- @Pointcut("execution(* com.itheima.service.*Service.*(..))")
- private void servicePt(){}
-
- //设置环绕通知,在原始操作的运行前后记录执行时间
- @Around("ProjectAdvice.servicePt()")
- public void runSpeed(ProceedingJoinPoint pjp) throws Throwable {
- //获取执行的签名对象
- Signature signature = pjp.getSignature();
- String className = signature.getDeclaringTypeName();
- String methodName = signature.getName();
-
- long start = System.currentTimeMillis();
- for (int i = 0; i < 10000; i++) {
- pjp.proceed();
- }
- long end = System.currentTimeMillis();
- System.out.println("万次执行:"+ className+"."+methodName+"---->" +(end-start) + "ms");
- }
-
- }

- <dependencies>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>5.2.10.RELEASEversion>
- dependency>
- <dependency>
- <groupId>org.aspectjgroupId>
- <artifactId>aspectjweaverartifactId>
- <version>1.9.4version>
- dependency>
- dependencies>
- public interface BookDao {
- public String findName(int id);
- }
- @Repository
- public class BookDaoImpl implements BookDao {
-
- public String findName(int id) {
- System.out.println("id:"+id);
- return "itcast";
- }
- }
- @Configuration
- @ComponentScan("com.itheima")
-
- public class SpringConfig {
- }
- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
-
- @Before("pt()")
- public void before() {
- System.out.println("before advice ..." );
- }
-
- @After("pt()")
- public void after() {
- System.out.println("after advice ...");
- }
-
- @Around("pt()")
- public Object around() throws Throwable{
- Object ret = pjp.proceed();
- return ret;
- }
- @AfterReturning("pt()")
- public void afterReturning() {
- System.out.println("afterReturning advice ...");
- }
-
-
- @AfterThrowing("pt()")
- public void afterThrowing() {
- System.out.println("afterThrowing advice ...");
- }
- }
- public class App {
- public static void main(String[] args) {
- ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
- BookDao bookDao = ctx.getBean(BookDao.class);
- String name = bookDao.findName(100);
- System.out.println(name);
- }
- }
- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @Before("pt()")
- public void before(JoinPoint jp)
- Object[] args = jp.getArgs();
- System.out.println(Arrays.toString(args));
- System.out.println("before advice ..." );
- }
- //...其他的略
- }
- public interface BookDao {
- public String findName(int id,String password);
- }
- @Repository
- public class BookDaoImpl implements BookDao {
- public String findName(int id,String password) {
- System.out.println("id:"+id);
- return "itcast";
- }
- }
- public class App {
- public static void main(String[] args) {
- ApplicationContext ctx = new
- AnnotationConfigApplicationContext(SpringConfig.class);
- BookDao bookDao = ctx.getBean(BookDao.class);
- String name = bookDao.findName(100,"itheima");
- System.out.println(name);
- }
- }
- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @Around("pt()")
- public Object around(ProceedingJoinPoint pjp)throws Throwable {
- Object[] args = pjp.getArgs();
- System.out.println(Arrays.toString(args));
- Object ret = pjp.proceed();
- return ret;
- }
- //其他的略
- }

- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @Around("pt()")
- public Object around(ProceedingJoinPoint pjp) throws Throwable{
- Object[] args = pjp.getArgs();
- System.out.println(Arrays.toString(args));
- args[0] = 666;
- Object ret = pjp.proceed(args);
- return ret;
- }
- //其他的略
- }
- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @Around("pt()")
- public Object around(ProceedingJoinPoint pjp) throws Throwable{
- Object[] args = pjp.getArgs();
- System.out.println(Arrays.toString(args));
- args[0] = 666;
- Object ret = pjp.proceed(args);
- return ret;
- }
- //其他的略
- }
- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @AfterReturning(value = "pt()",returning = "ret")
- public void afterReturning(Object ret) {
- System.out.println("afterReturning advice ..."+ret);
- }
- //其他的略
- }
运行App后查看运行结果,说明返回值已经被获取到

- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @Around("pt()")
- public Object around(ProceedingJoinPoint pjp){
- Object[] args = pjp.getArgs();
- System.out.println(Arrays.toString(args));
- args[0] = 666;
- Object ret = null;
- try{
- ret = pjp.proceed(args);
- }catch(Throwable throwable){
- t.printStackTrace();
- }
- return ret;
- }
- //其他的略
- }
- @Component
- @Aspect
- public class MyAdvice {
- @Pointcut("execution(* com.itheima.dao.BookDao.findName(..))")
- private void pt(){}
- @AfterThrowing(value = "pt()",throwing = "t")
- public void afterThrowing(Throwable t) {
- System.out.println("afterThrowing advice ..."+t);
- }
- //其他的略
- }
- @Repository
- public class BookDaoImpl implements BookDao {
- public String findName(int id,String password) {
- System.out.println("id:"+id);
- if(true){
- throw new NullPointerException();
- }
- return "itcast";
- }
- }
运行App后,查看控制台,就能看的异常信息被打印到控制台

至此,AOP通知如何获取数据就已经讲解完了,数据中包含参数、返回值、异常(了解)。
需求: 对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理。

- public interface ResourcesService {
- public boolean openURL(String url ,String password);
-
- }
- @Service
- public class ResourcesServiceImpl implements ResourcesService {
- @Autowired
- private ResourcesDao resourcesDao;
-
- public boolean openURL(String url, String password) {
- return resourcesDao.readResources(url,password);
- }
- }
- public interface ResourcesDao {
-
- boolean readResources(String url, String password);
- }
- @Repository
- public class ResourcesDaoImpl implements ResourcesDao {
- public boolean readResources(String url, String password) {
- System.out.println(password.length());
- //模拟校验
- return password.equals("root");
- }
- }
- @Configuration
- @ComponentScan("com.itheima")
- @EnableAspectJAutoProxy
- public class SpringConfig {
- }
- @Component
- @Aspect
- public class DataAdvice {
- @Pointcut("execution(boolean com.itheima.service.*Service.*(*,*))")
- private void servicePt(){}
-
- @Around("DataAdvice.servicePt()")
- public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {
- Object[] args = pjp.getArgs();
- for (int i = 0; i < args.length; i++) {
- //判断参数是不是字符串
- if(args[i].getClass().equals(String.class)){
- args[i] = args[i].toString().trim();
- }
- }
- Object ret = pjp.proceed(args);
- return ret;
- }
-
-
- }
- public class App {
- public static void main(String[] args) {
- ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
- ResourcesService resourcesService = ctx.getBean(ResourcesService.class);
- boolean flag = resourcesService.openURL("http://pan.baidu.com/haha", "root ");
- System.out.println(flag);
- }
- }

AOP的知识就已经讲解完了,接下来对于AOP的知识进行一个总结:
execution(* com.itheima.service.*Service.*(..))
切入点表达式书写技巧
笔记来自: 黑马程序员SSM框架教程