三天掌握Spring系列第二讲 AOP 方法增强就是这么简单

SpringAOP

6AOP

6.1AOP

AOP Aspect Oriented Programming

使使使使

6.2AOP

  • 便

6.3AOP

使

7AOP

7.1

CRUD

使 connection setAutoCommit(true)

sql sql

 
 
 void transfer(String sourceName,String targetName,Float money);
 
 
 
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        //
        User source = userDao.findByName(sourceName);
        User target = userDao.findByName(targetName);
        //
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        //
        userDao.update(source);
        //
        int i = 1 / 0
       userDao.update(target)
   }

7.2

TransactionManager

 package cn.fage.manager;
 
 import javax.sql.DataSource;
 
 /**
  * @author lin
  * @version 1.0
  * @date 2020-08-11 14:45
  * @Description TODO
  */
 public class TransactionManager {
 
    private DataSource connectionUtils;
 
    public void setConnectionUtils(DataSource connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
 
    /**
      * 
      */
    public void beginTransaction(){
        try {
            connectionUtils.getConnection().setAutoCommit(false);
        }catch (Exception e){
            e.printStackTrace()
       
   }  

   /*
     * 务 
     *
   public void commit()
       try 
           connectionUtils.getConnection().commit()
       }catch (Exception e)
           e.printStackTrace()
       
   }  

   /*
     * 务 
     *
   public void rollback()
       try 
           connectionUtils.getConnection().rollback()
       }catch (Exception e)
           e.printStackTrace()
       
   }   


   /*
     * 接 
     *
   public void release()
       try 
           connectionUtils.getConnection().close();//中 
       }catch (Exception e)
           e.printStackTrace()
       
   

使springIoc

 /**
  * 
  *
  * 
  */
 package cn.fage.spring.impl;
 
 import cn.fage.manager.TransactionManager;
 import cn.fage.pojo.User;
 import cn.fage.spring.UserDao;
 import cn.fage.spring.UserService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.stereotype.Service;
 
 import java.util.List;
 
 /**
  * @author lin
  * @version 1.0
  * @date 2020-08-10 11:17
  * @Description TODO
  */
 public class UserServiceImpl2 implements UserService {  

   private UserDao userDao;  

   private TransactionManager txManager;  

   @Overrid
   public User saveUser(User user) 
       return userDao.saveUser(user)
   }  

   @Overrid
   public void transfer(String sourceName, String targetName, Float money) 
       try 
           //1.务 
           txManager.beginTransaction()
           //2.作 
           List<User> accounts = userDao.findAllUser()
           //3.务 
           txManager.commit()
       }catch (Exception e)
           //5.作 
           txManager.rollback()
           throw new RuntimeException(e)
       }finally 
           //6.接 
           txManager.release()
       
   

7.3

使

7.4

7.4.1

7.4.2

    • JDK Proxy

    • CGLib asmxxxx asm.jar

    • final

7.2.5

 /**
  * Service
  */
 package cn.fage.factory;
 
 import cn.fage.manager.TransactionManager;
 import cn.fage.spring.UserService;
 
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 
 /**
  * @author lin
  * @version 1.0
  * @date 2020-08-11 14:52
  * @Description Service
  */
 public class BeanFactory {
 
    private UserService userService;
 
    private TransactionManager txManager;
 
    public void setTxManager(TransactionManager txManager) 
       this.txManager = txManager
   }   


   public final void setAccountService(UserService userService) 
       this.userService = userService
   }  

   /*
     * Service象 
     
     * @retur
     *
   public UserService getAccountService() 
       return (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader()
               userService.getClass().getInterfaces()
               new InvocationHandler() 
                   /*
                     * 持 
                     
                     * @param prox
                     * @param metho
                     * @param arg
                     * @retur
                     * @throws Throwabl
                     *
                   @Overrid
                   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  

                       if ("test".equals(method.getName())) 
                           return method.invoke(userService, args)
                       }  

                       Object rtValue = null
                       try 
                           //1.务 
                           txManager.beginTransaction()
                           //2.作 
                           rtValue = method.invoke(userService, args)
                           //3.务 
                           txManager.commit()
                           //4.果 
                           return rtValue
                       } catch (Exception e) 
                           //5.作 
                           txManager.rollback()
                           throw new RuntimeException(e)
                       } finally 
                           //6.接 
                           txManager.release()
                       
                   
               })
   

8 SpringAOP[]

8.1 SpringAOP

8.1.1

spring aop

8.1.2 AOP

  • Joinpoiont()

    spring ,, spring

  • Pointcut()

    Joinpoint

  • Advice(/)

    Joinpoint

    ,,,,

  • Introduction()

    , Introduction Field

  • Target()

  • Weaving()

    spring AspectJ

  • Proxy()

    AOP

  • Aspect()

8.1.3 springAOP

a

线

bSpring

Spring 使

8.1.4

spring

8.2 XMLAOP

spring aop spring ioc AOP

8.2.1

8.2.1.1 pom.xml

 <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.8.RELEASE</version>
    </dependency>
 
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.7</version>
    </dependency>
 </dependencies>

8.2.1.2 springbean.xml

aop

 <?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:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
 </beans>

8.2.1.3 springioc

 <!-- srpingIoc,service-->
 <bean id="userService" class="cn.fage.spring.impl.UserServiceImpl"></bean>

8.2.1.4

 /**
  * 
  */
 public class Logger {
 
    /**
      * 
      */
    public void beforePrintLog(){
        System.out.println("LoggerbeforePrintLog");
    }
 
    /**
      * 
      */
    public void afterReturningPrintLog(){
        System.out.println("LoggerafterReturningPrintLog");
    }
    /**
      * 
      */
    public void afterThrowingPrintLog(){
        System.out.println("LoggerafterThrowingPrintLog");
    }
 
    /*
     * 知 
     *
   public void afterPrintLog()
       System.out.println("LoggerafterPrintLog")
   }  

   /*
     * 知 
     * : 
     *     。 
     * : 
     *     。 
     * : 
     *     SpringProceedingJoinPointproceed()。 
     *     spring使。 
     
     * spring: 
     *     spring。 
     *
   public Object aroundPrintLog(ProceedingJoinPoint pjp)
       Object rtValue = null
       try
           Object[] args = pjp.getArgs();//数 
           System.out.println("LoggeraroundPringLog")
           rtValue = pjp.proceed(args);//) 
           System.out.println("LoggeraroundPringLog")
           return rtValue
       }catch (Throwable t)
           System.out.println("LoggeraroundPringLog")
           throw new RuntimeException(t)
       }finally 
           System.out.println("LoggeraroundPringLog")
       
   
}

8.2.2

8.2.2.1 bean

<!-- Logger -->
<bean id="logger" class="cn.fage.util.Logger"></bean>

8.2.2.2 使 aop:config aop

aop:config

aop

<aop:config>
<!-- -->
</aop:config>

8.2.2.3 使 aop:aspect

aop:aspect

  • id

  • ref bean id

    <aop:aspect id="logAdvice" ref="logger">

    /aop:aspect

8.2.2.4 使 aop:pointcut

aop:pointcut

  • expression

  • id

aop:aspect使aop:aspect

<aop:pointcut id="pt1" expression="execution(* cn.fage.service.impl.*.*(..))"></aop:pointcut>

8.2.2.5 使 aop:xxx

aop:before

  • method

  • ponitcut-ref

  • poinitcut

:

<aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>

aop:after-returning

  • method

  • ponitcut-ref

  • poinitcut

:

<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>

aop:after-throwing

  • method

  • ponitcut-ref

  • poinitcut

:

<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>

aop:after

  • method

  • ponitcut-ref

  • poinitcut

:

aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>

8.2.3

execution:()

execution()

execution([] ..())

    • public void cn.fage.service.impl.UserServiceImpl.saveUser(cn.fage.pojo.User)

  • 访

    • void cn.fage.service.impl.UserServiceImpl.saveUser(cn.fage.pojo.User)

  • 使*

    • * cn.fage.service.impl.UserServiceImpl.saveUser(cn.fage.pojo.User)

  • 使

    • * *.*.*.*.UserServiceImpl.saveUser(cn.fage.pojo.User)

  • 使..

    • * cn..UserServiceImpl.saveUser(cn.fage.pojo.User)

  • 使*

    • * cn..*.saveUser(cn.fage.pojo.User)

  • 使*

    • * cn..*.*( cn.fage.pojo.User)

  • 使*

    • * cn..*.*(*)

  • 使..

    • * cn..*.*(..)

    • * *..*.*(..)

:

execution(``* cn.fage.service.impl.*.*(..)``)

8.2.4

<aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>

aroundPrintLog

aop:around

  • method

  • ponitcut-ref

  • poinitcut

spring

使

8.3 AOP

8.3.1

8.3.1.1 pom.xml

XMLAOPpom.xml

8.3.1.2 context

<?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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

</beans>

8.3.1.3 使

/**
*
*/
@Service("usertService")
public class UserServiceImpl implements UserService{

}

8.3.1.4 spring

<!-- spring-->
<context:component-scan base-package="cn.fage"></context:component-scan>

8.3.2

8.3.2.1 使

@Component("logger")
public class Logger {

}

8.3.2.2 使@Aspect

@Component("logger")
@Aspect//
public class Logger {

}

8.3.2.3 使

@Before

value

/**
*
*/
@Before("execution(* cn.fage.service.impl.*.*(..))")
public void beforePrintLog(){
System.out.println("LoggerbeforePrintLog");
}

@AfterReturning

value

/**
*
*/
@AfterReturning("execution(* cn.fage.service.impl.*.*(..))")
public void afterReturningPrintLog(){
System.out.println("LoggerafterReturningPrintLog");
}

@AfterThrowing

value

/**
*
*/
@AfterThrowing("execution(* cn.fage.service.impl.*.*(..))")
public void afterThrowingPrintLog(){
System.out.println("LoggerafterThrowingPrintLog");
}

@After

value

/**
*
*/
@After("execution(* cn.fage.service.impl.*.*(..))")
public void afterPrintLog(){
System.out.println("LoggerafterPrintLog");
}

8.3.2.4 spring spring AOP

<!-- springAOP -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

8.3.3

@Around

value

@Around("execution(* cn.fage.service.impl.*.*(..))")
public Object aroundPringLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//

System.out.println("LoggeraroundPringLog");

rtValue = pjp.proceed(args);//

System.out.println("LoggeraroundPringLog");

return rtValue;
}catch (Throwable t){
System.out.println("LoggeraroundPringLog");
thrownewRuntimeException(t);
}finally{
System.out.println("LoggeraroundPringLog");
}}

8.3.4

@Pointcut

value

@Pointcut("execution(* cn.fage.service.impl.*.*(..))")
private void pt1() {}

@Around("execution(* cn.fagea.service.impl.*.*(..))")

Pointcut

@Around("pt1()")//

8.3.5 使XML

@Configuration
@ComponentScan(basePackages="cn.fage")
@EnableAspectJAutoProxy // spring AOP
public class SpringConfiguration {
}

package cn.fage.test.aop;

import cn.fage.configuration.ApplicationContextUtil;
import cn.fage.configuration.SpringConfiguration;
import cn.fage.pojo.User;
import cn.fage.spring.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

/**
* @author lin
* @version 1.0
* @date 2020-08-11 15:23
* @Description TODO
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=SpringConfiguration.class)
publicclassRunnerTest{

@Test
publicvoidtest01(){
ApplicationContextcontext=ApplicationContextUtil.getApplicationContext();
for(Stringname:context.getBeanDefinitionNames()){
System.out.println(name);
}
UserServiceuserService=(UserService)context.getBean("userService");
userService.saveUser(null);
}}


VM, : ''127.0.0.1:59765', transport: ''', : '{1}'
8 11, 2020 3:33:41 org.springframework.test.context.support.AbstractTestContextBootstrapper getDefaultTestExecutionListenerClassNames
: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener,org.springframework.test.context.support.DirtiesContextTestExecutionListener,org.springframework.test.context.transaction.TransactionalTestExecutionListener,org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener,org.springframework.test.context.event.EventPublishingTestExecutionListener]
811,20203:33:41org.springframework.test.context.support.AbstractTestContextBootstrappergetTestExecutionListeners
:UsingTestExecutionListeners:[org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@1283bb96,org.springframework.test.context.support.DependencyInjectionTestExecutionListener@74f0ea28,org.springframework.test.context.support.DirtiesContextTestExecutionListener@f6efaab,org.springframework.test.context.transaction.TransactionalTestExecutionListener@3c19aaa5,org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@3349e9bb,org.springframework.test.context.event.EventPublishingTestExecutionListener@409bf450]
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
springConfiguration
applicationContextUtil
dataSourceConfigs
userConfigs
userDao
userService
logger
dataSource1
dataSource2
user2
user
org.springframework.aop.config.internalAutoProxyCreator
LoggeraroundPringLog
LoggerbeforePrintLog
LoggeraroundPringLog
LoggerbeforePrintLog
org.springframework.jdbc.datasource.DriverManagerDataSource@36b0fcd5savenull
LoggerafterReturningPrintLog
LoggerafterPrintLog
LoggeraroundPringLog
LoggeraroundPringLog
LoggerafterReturningPrintLog
LoggerafterPrintLog
LoggeraroundPringLog
LoggeraroundPringLog
VM,:''127.0.0.1:59765',transport:''',:'{1}'

,退0

ApplicationContextbean

package com.ba.cloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
importorg.springframework.stereotype.Component;

importjavax.sql.DataSource;

@Component
publicclassApplicationContextProvider
implementsApplicationContextAware{

@Autowired
DynamicDataSourceConfigdynamicDataSourceConfig;
@Autowired
DataSourcedataSource;

publicstaticDataSourcedataSourceHelp;

/**
*
*/
privatestaticApplicationContextapplicationContext;

@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{
ApplicationContextProvider.applicationContext=applicationContext;
dataSourceHelp=dataSource;
ConfigurableApplicationContextconfigurableApplicationContext=(ConfigurableApplicationContext)applicationContext;
//beanDefaultListableBeanFactory
DefaultListableBeanFactorydefaultListableBeanFactory=(DefaultListableBeanFactory)configurableApplicationContext.getBeanFactory();
for(DynamicDataSourceConfig.DataSourcedatasouce:dynamicDataSourceConfig.getDatasouces()){
DruidDataSourcedruidDataSource=newDruidDataSource();
druidDataSource.setUsername(datasouce.getUsername());
druidDataSource.setPassword(datasouce.getPassword());
druidDataSource.setUrl(datasouce.getUrl());
druidDataSource.setDriverClassName(datasouce.getDriver());
//BeanDefinitionBuilderbean
BeanDefinitionBuilderbeanDefinitionBuilder=BeanDefinitionBuilder.genericBeanDefinition(DataSource.class);
//bean
defaultListableBeanFactory.registerBeanDefinition(datasouce.getName(),beanDefinitionBuilder.getRawBeanDefinition());
defaultListableBeanFactory.registerSingleton(datasouce.getName(),druidDataSource);
}
}

/**
*applicationContext
*
*@return
*/
publicstaticApplicationContextgetApplicationContext(){
returnapplicationContext;
}

/**
*nameBean.
*
*@paramname
*@return
*/
publicstaticObjectgetBean(Stringname){
returngetApplicationContext().getBean(name);
}

/**
*classBean.
*
*@paramclazz
*@param<T>
*@return
*/
publicstatic<T>TgetBean(Class<T>clazz){
returngetApplicationContext().getBean(clazz);
}

/**
*name,ClazzBean
*
*@paramname
*@paramclazz
*@param<T>
*@return
*/
publicstatic<T>TgetBean(Stringname,Class<T>clazz){
returngetApplicationContext().getBean(name,clazz);
}

}

QQ

img

如果你觉得文章还不错,就请点击右上角选择发送给朋友或者转发到朋友圈~

● 扫码关注我们

据说看到好文章不推荐的人,服务器容易宕机!

本文版权归 发哥讲博客园 共有,原创文章,未经允许不得转载,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/naimao/p/13476565.html