Ape metamorphosis 15 - Spring AOP just looks good

Posted by Roja on Wed, 10 Jun 2020 03:13:17 +0200

Having read the previous metamorphosis series, I'm sure you have an understanding of mybatis in its application.But it's not enough to complete your metamorphosis. Considering your basics, let's go back to spring and talk about AOP.

Ape metamorphosis is also an original series of articles to help you start from a common white, master some common framework technology knowledge in the industry, and exercise your ability to improve system design, complete your metamorphosis, more exciting content, please pay attention to the Princess Ape Man Factory, click on Ape Man to develop!

 

 

 

 

 

 

 

 

Spring certainly supports the programming idea of AOP.AspectJ is also an AOP programming framework, which is simple to implement, easy to use, and supports annotations. Spring's AOP implementation of AspectJ after version 2.0 is included in its own battlefield, but it still needs Spring AOP to do this step when the code will be woven into it.Generally speaking, using Spring's AOP module, AspectJ's implementation is commonly used.

 

Next we'll use an example of xml to do an AOP programming.

modifyPom.xmlIncrease dependency:

<!--  Use AOP join aspectj rely on-->       <dependency>                     <groupId>org.aspectj</groupId>                     <artifactId>aspectjweaver</artifactId>                     <version>1.7.4</version>              </dependency>   <!--  Use AOP join Spring Yes AOP Of aspectj Support dependency-->              <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-aspects</artifactId>        <version>4.1.2.RELEASE</version>    </dependency>

 

Code example:

To demonstrate the effect, add a method to TravelRouteService:

package com.pz.study.frame.spring.service; import java.util.List; import com.pz.study.frame.spring.domain.TravelRoute;  /** * Line Service */public interface TravelRouteService {      /**     * Query by id     * @param rid     * @return     */    public TravelRoute findTravelRouteById(StringtravelRouteId);          /**     * Line change required     * @param rid     * @return     */    public TravelRoute updateTravelRouteById(StringtravelRouteId);          /**     * Delete Line     * @param rid     * @return     */    public TravelRoute deleteTravelRouteById(StringtravelRouteId);       /**     * Paging Query Line List     * @param startRow     * @param endRow     * @return     */    public List<TravelRoute>findTravelRouteByPage(int startRow ,int endRow);       /**     * Add Line     * @param travelRoute     * @throws Exception     */    public void addTravelRoute(TravelRoute travelRoute) throws Exception;}

 

 

Modify the implementation class:

package com.pz.study.frame.spring.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.pz.study.frame.spring.domain.TravelRoute;import com.pz.study.frame.spring.manager.TravelRouteManager;import com.pz.study.frame.spring.service.TravelRouteService;package com.pz.study.frame.spring.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.pz.study.frame.spring.domain.TravelRoute;import com.pz.study.frame.spring.manager.TravelRouteManager;import com.pz.study.frame.spring.service.TravelRouteService; @Service(value="TravelRouteService")public class TravelRouteServiceImpl implements TravelRouteService {             @Resource(name="travelRouteManager")       private TravelRouteManager travelRouteManager;             public TravelRouteServiceImpl(){              System.out.println("TravelRouteServiceImpl Instantiated");       }        @Override       public TravelRoute findTravelRouteById(StringtravelRouteId) {              System.out.println("=====findTravelRouteById=====Executed");              returntravelRouteManager.findTravelRouteById(travelRouteId);       }                                  @Override       public TravelRoute updateTravelRouteById(StringtravelRouteId) {                           System.out.println("=====updateTravelRouteById=====Executed");              returnnull;                                  }        @Override       public TravelRoute deleteTravelRouteById(StringtravelRouteId) {              System.out.println("=====deleteTravelRouteById=====Executed");              returnnull;                                  }        @Override       public List<TravelRoute>findTravelRouteByPage(int startRow, int endRow) {              System.out.println("=====findTravelRouteByPage=====Executed");              return null;       }                    @Override       public void addTravelRoute(TravelRoute travelRoute) throws Exception {                           System.out.println("=====addTravelRoute=====Executed");                           thrownew Exception("addTravelRoute===Exception");                    }        public void init() {          System.out.println("I'm the initial method init I was executed");       }        public void destroy() {          System.out.println("I'm the destruction method destroy I was executed");       }        public void setTravelRouteManager(TravelRouteManager travelRouteManager) {              this.travelRouteManager = travelRouteManager;       }             } 

 

 

Write the facet class FristAspect:

package com.pz.study.frame.spring.aspect; import org.aspectj.lang.ProceedingJoinPoint; public class FristAspect {        public void before() {              System.out.println("===before====Pre-method Enhancement========");       }        public void after() {              System.out.println("===after=====Final Enhancement========");       }        public void afterThrowing(Exception e) {              System.out.println("===afterThrowing=====Exception Notification========:" + e);       }        public void afterReturning(int result) {              System.out.println("===afterReturning=====Notification Enhancement After Return========" + result);       }        public Object around(ProceedingJoinPoint pjp) throws Throwable {              System.out.println("===around=====Surround Enhancement:Front========:");              Object proceed = pjp.proceed();              System.out.println("===around=====Surround Enhancement:after========:");               return proceed;       }}

 

Write Spring AOP related configuration file spring-aop.xml, Profile:

 

<?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">        <!-- injection Aspect Implementation Class --><bean id="fristAspect"class="com.pz.study.frame.spring.aspect.FristAspect"/>   <!-- injection Aspect Implementation Class -->    <bean id="fristAspect"class="com.pz.study.frame.spring.aspect.FristAspect"/>      <!--To configure aop-->    <aop:config>        <!--Define entry points-->        <aop:pointcut id="addTravelRoutePointcut" expression="execution(* com.pz.study.frame.spring.service.impl.TravelRouteServiceImpl.addTravelRoute(..))"/>        <aop:pointcut id="updateTravelRouteByIdPointcut" expression="execution(*com.pz.study.frame.spring.service.impl.TravelRouteServiceImpl.updateTravelRouteById(..))"/>        <aop:pointcut id="deleteTravelRouteByIdPointcut" expression="execution(*com.pz.study.frame.spring.service.impl.TravelRouteServiceImpl.deleteTravelRouteById(..))"/>        <aop:pointcut id="findTravelRouteByIdPointcut" expression="execution(* com.pz.study.frame.spring.service.impl.TravelRouteServiceImpl.findTravelRouteById(..))"/>        <aop:pointcut id="findTravelRouteByPagePointcut" expression="execution(* com.pz.study.frame.spring.service.impl.TravelRouteServiceImpl.findTravelRouteByPage(..))"/>         <!--Define Faces-->        <aop:aspect ref="fristAspect">            <!--Pre-Enhancement-->            <aop:before method="before" pointcut-ref="updateTravelRouteByIdPointcut"/>            <!--Post Enhancement-->            <aop:after-returning method="afterReturning" pointcut-ref="deleteTravelRouteByIdPointcut" returning="result"/>            <!--Abnormal Enhancement-->            <aop:after-throwing method="afterThrowing" pointcut-ref="addTravelRoutePointcut" throwing="e"/>            <!--Final Enhancement-->            <aop:after method="after"pointcut-ref="findTravelRouteByIdPointcut"/>            <!--Surround Enhancement-->            <aop:around method="around" pointcut-ref="findTravelRouteByPagePointcut"/>        </aop:aspect>    </aop:config>

 

Don't forget toApplicationContext.xmlIntroduce new profile oh

  <importresource="spring-aop.xml"/>

Write a test case to feel the effect:

 

@Test       public void testAop(){                            ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");                              TravelRouteController travelRouteController=(TravelRouteController)applicationContext.getBean("travelRouteController");               TravelRouteServicetravelRouteService=(TravelRouteService) applicationContext.getBean("travelRouteService");                              travelRouteService.findTravelRouteById("testAop");               travelRouteService.updateTravelRouteById("testAop");               travelRouteService.deleteTravelRouteById("testAop");               travelRouteService.findTravelRouteByPage(0,10);                              try {                     travelRouteService.addTravelRoute(new TravelRoute());              } catch (Exception e) {                     // TODO Auto-generated catch block                     e.printStackTrace();              }                                 }

 

===after======Final enhancement=========

====before====method preceding enhancement========

=====updateTravelRouteById=====Executed

=====deleteTravelRouteById=====Executed

====around=====Enhancement of surround: Front========:

=====findTravelRouteByPage=====Executed

====around=====Enhancement of surround: After========:

=====addTravelRoute=====executed

====afterThrowing=====Exception Notification=========:java.lang.Exception: addTravelRoute===Exception

<Aop:config>Label, which defines a set of AOP configurations.

<Aop:ponintcut>Sublabel, define the entry point, id represents the unique number of the entry point, expression is the value of the entry point, need to satisfy excution expression

<Aop:aspect>The ref attribute of the self-tag, specifying which facet to use.

<Aop:before>Define the pre-enhancement, method is the method name in the faceted bean, and specify the use of the method in the facet to implement the enhancement.

<Aop:after>Define the final enhancement, method is the method name in the faceted bean s, and specify the use of the method in the facet to implement the enhancement.

<Aop:after-returning>Define the post-return enhancements, method is the method name in the faceted bean s, and specify the use of the methods in the facets for enhancements.

<Aop:after-throwing>Define the exception enhancement, method is the method name in the faceted bean, specify the method in the facet to use for enhancement.

<Aop:around>Define wrapping enhancements, method is the method name in the faceted bean s, and specify the use of the method in the facets for enhancements.

AspectJ provides an excution expression to define a starting point, with the following expression syntax:

execution (

* Access permission type [modifiers-pattern]

ret-type-pattern return value type

* Fully qualified class name [declaring-type-pattern]

name-pattern(param-pattern) method name (parameter name)

throws-pattern throws an exception type

)

 

The definition of the entry point requires a method name that matches the target. When using the excution expression, the [] section can be omitted and the sections are separated by spaces.

Here are some examples of expressions.

Give an example:

execution(public * *(..))

Formal Meaning: Any public method.

 

execution(* set*(..))

Formal Meaning: Any method that starts with "set".

 

execution(* com.pz.study.frame.spring.service*.*(..))

Formal Meaning: Defined inCom.pz.study.Frame.spring.serviceAll classes and methods in the package.

 

execution(* com.pz.study.frame.spring.service..*.*(..))

Formal Meaning: Defined inCom.pz.study.Frame.spring.serviceAll classes and methods in a package or subpackage.

Note: When'. 'appears in an expression, it must be followed by'*' to represent all classes under a package or subpackage.

 

execution(* *.service.*.*(..))

Formal meaning: Only all methods in all classes (interfaces) under the serivce subpackage under the first level package are starting points

 

execution(* *..service.*.*(..))

Formal Meaning: All methods in all classes (interfaces) under serivce subpackages under all packages are starting points

 

execution(* *.IService.*(..))

Formal Meaning: All methods in the IService interface under Level 1 packages are starting points

 

execution(* *.. IService.*(..))

Formal Meaning: All methods in the IService interface under all packages are starting points

 

execution(*com.pz.study.frame.spring.service.TravelRouteService.*(..))

Formal Meaning:Com.pz.study.Frame.spring.serviceAll methods in the.TravelRouteService interface.

 

execution(*com.pz.study.frame.spring.service.TravelRouteService+.*(..))

Formal Meaning:Com.pz.study.Frame.spring.serviceIf TravelRouteService is an interface, it is all the methods in the interface and all the methods in all the implementation classes; if it is a class, it is all the methods in the class and its subclasses.

I have built a technical group, there are many masters in the group, add small edition WeChat, Note: Learn.Take you to see more masters and help you grow quickly.

Topics: Spring xml Java Programming