An overview of the

SSM framework is currently commonly used framework, that framework is what le, in simple terms, the framework is someone else has written software, has written templates, simplify our development. If we need to do other development later, we just need to add and remove some.

SSM frameworks are: Spring: Service processing framework, mainly for object creation and some business processing SpringMVC: mainly for some request processing Mybatis: database processing, JDBC strengthening

The Spring Framework

1. The introduction of the Spring

Spring is a lightweight Java development framework that emerged in 2003 to address enterprise application development

Of the complexity created by. At the heart of Spring are inversion of Control (IoC) and section-oriented programming (AOP). Spring is a lightweight open source framework that can be used in Java SE/EE.

2. The advantages of Spring

  1. lightweight
  2. decoupling
  3. Support AOP
  4. Easy integration with other frameworks

3. The Spring architecture diagram

Just take a look here. It looks familiar, but you may not understand it now. You can come back when you know more about it

4.IOC inversion of control

An IoC is an Inversion of Control. Refers to will traditionally be replaced by a program

Code directly control the object call power to the container, through the container to achieve the assembly and management of the object. Inversion of control is a transfer of object control from the program code itself to an external container. Through the container to achieve object creation, attribute assignment, dependency management.

In a nutshell: earlier we created an object by creating it with new. For example: create a Data object new Data (), but now we do not need to create objects in the framework itself, the framework container will automatically create objects and assign values, what is the container, can be considered as an object to hold things.

IOC is realized by Dependency Injection (DI).

Dependency injection DI means that the program does not need to be created in code if it needs to call another object to assist it

The caller, instead, depends on the external container, which is created and passed to the program.

5. The first Spring program

5.1 Creating a Maven project

To create a Maven project, select the template QuickStart. In fact, you can skip the template and create an empty project, but the advantage of choosing the template is that it will create the appropriate folder for us. If not, we will create the appropriate directory ourselves

5.2 Then add Spring’s dependencies to the pom.xml file in Maven

<! --> <dependency> <groupId>org.springframework</groupId> <artifactId> Spring context</artifactId> < version > 5.2.5. RELEASE < / version > < / dependency >Copy the code

5.3 Defining interfaces and implementing interface entity classes

Interface:

public interface SomeService {
    public void doSome();
}
Copy the code

Entity class

public class SomeServiceImpl implements SomeService { public void doSome() { System.out.println("dosome"); }}Copy the code

5.4 Writing the Spring Configuration File

Create a new configuration file in the Resources directory, usually named applicationContext.xml

5.5 Writing bean Labels

Id: custom name of the object, unique value. Spring finds the object name by this name: a custom name for the object that can have multiple values. Class: the fully qualified name of a class (cannot be an interface, because spring is a reflection mechanism to create objects and must use classes). Can Spring create an object that is not a custom class, create an object of an existing class.

 <bean name="doSomeService1,doSomeService2" class="com.springtest.service.impl.SomeServiceImpl"/>
 <bean id="doSomeService3" class="com.springtest.service.impl.SomeServiceImpl"/>
 <bean id="mydate" class="java.util.Date" />
Copy the code

5.6 Writing test Classes

public class MyTest { @Test public void test1() { String config = "applicationContext.xml"; ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(config); SomeService doSomeService = (SomeService) classPathXmlApplicationContext.getBean("doSomeService1"); doSomeService.doSome(); }}Copy the code

6. Xml-based DI

After the bean instance calls the no-argument constructor to create the object, it initializes the properties of the bean object. Initialization is done automatically by the container and is called injection.

According to the different injection methods, there are two commonly used types: set injection and construct injection.

6.1 set injection

Set injection: Spring calls the class’s set method, where you can do property assignment

6.1.1 Set injection of simple types

<bean id=" XXX "class="yyy"> <property name=" value" =" value "/> </bean>Copy the code

6.1.2 Set Injection for reference types: Spring calls the class’s set method

The value of ref must be the ID value of a bean.

<bean id=" XXX "class="yyy"> <property name=" attribute name" /> </bean>Copy the code

6.1.3 Set Injection Example

1. Create entity class Student
public class Student { private String name; private int id; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", id=" + id + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; }}Copy the code
2. Compile the applicationContext. XML file
<bean id="student" class="domain. student" > <property name="id" value="1"/> <property name="name" value=" zhang 三"/> <! --set injection, if the attribute is an object, use ref="" to assign --> </bean>Copy the code
3. Write test classes
public class MyTest { @Test public void test(){ String config = "applicationContext.xml"; ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(config); Student st = (Student) classPathXmlApplicationContext.getBean("student"); System.out.println(st.toString()); }}Copy the code

==set injection When assigning a property, ensure that the entity class has the set method ==

6.2 Construction Injection

Constructor injection: Spring calls classes have parameter constructors that assign values to properties while creating objects. Constructor injection uses the <constructor-arg> tag: a <constructor-arg> denotes a constructor argument. <constructor-arg> Tag attributes: name: indicates the name of the constructor's parameter index: indicates the position of the constructor's parameters in the order of 0, 1, and 2 from left to right value: The constructor's parameter type is simple, using value ref: The constructor parameter type is referential and uses refCopy the code

6.3 Automatic Reference Type Injection

Automatic injection of reference types: The Spring framework can assign values to reference types according to certain rules. ByName, byType. 1. ByName (injected byName) : Spring can assign a bean to a reference type in a Java class whose attribute name is the same as the id name of the <bean> in the Spring container (configuration file) and whose data type is the same. Syntax: <bean id="xx" class="yyy" autowire="byName"> Simple type attribute assignment </bean> The datatype of a reference type in a Java class is homologous to the class property of the <bean> in the Spring container (configuration file). Such a bean can be assigned a value to the class property of a reference type. This means that the datatype of a reference type in a Java class is identical to the value of the bean's class. 2. Java class reference type data type and bean class value parent-class relationship. <bean id="xx" class="yyy" autowire="byType"> Simple type attribute assignment </bean>Copy the code

Note: In byType, only one qualified bean can be declared in an XML configuration file; more than one is an error ==

6.4 Specifying multiple Spring configuration files for your application

Included configuration file: spring-total Indicates the master configuration file: contains other configuration files. The master configuration file usually does not define objects. Syntax: <import resource=" path to other configuration files "/> "Classpath :" indicates the classpath (the directory where the class file resides). To specify the location of other files in Spring's configuration file, use classpath to tell Spring where to load and read files. For example, load each configuration file separately: <import resource="classpath:ba06/spring-school.xml" /> <import resource="classpath:ba06/spring-school.xml" /> In configuration files containing relationships, wildcards (* : for any character) can be used. Note: The name of the main configuration file cannot be included in the wildcard (cannot be called spring-total.xml). For example:  <import resource="classpath:ba06/spring-*.xml" />Copy the code

7. Annotation-based development

7.1 Creating Annotations for Objects

@Component: <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> Component does not specify an object name. Spring provides the default name: Class name lowercase @Component(value ="myStudent") equals <bean id="myStudent" class=" com.test.ba01.student "/> 1.@Repository (on top of the persistence layer class) : on top of the dao implementation class to create dao objects that can access the database. 2.@Service(used on top of the business layer class) : on top of the service implementation class, create the Service object, the service object is to do business, can have transactions and other functions. 3.@Controller(for controllers) : placed on top of the controller (processor) class to create controller objects that accept user-submitted parameters and display the processing results of requests. These three annotations use the same syntax as @Component. All can create objects, but these three annotations have additional functionality. @repository, @Service, and @Controller are hierarchies of project objects.Copy the code

7.2 Component-Scan

Declare component-scan, which is the Java object base-package: specify the package name of the annotations (PS: create object-related annotations) in your project. Component-scan works: Spring scans through the package specified by the Base-package, takes all classes in the package and subpackages, finds annotations in the class, and creates objects or assigns values to attributes based on the annotations. Added component-scan tag, configuration file changes: 1. Add a new constraint file spring-context.xsd 2. There are three ways to give the new constraint file a namespace name to specify multiple packages: <! -- The first way: Using multiple component scanners, <context:component-scan base-package="com.test.ba01"/> <context:component-scan base-package="com.test.ba02"/> <! Second way: use delimiters (; Or,) separate multiple package names --> <context:component-scan base-package="com.test.ba01; com.test.ba02" /> <! <context:component-scan base-package="com.test" />Copy the code

7.3 Developing examples using Annotations

7.3.1 Declare entity classes and use annotations to create objects

Example: entity class Student

@Component("myStudent") public class Student {private String name; private Integer age; Public Student() {system.out.println ("== Student no argument constructor ==="); } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code

7.3.2 Declare component scanner

<context:component-scan base-package="com.test.ba01" />
Copy the code

7.3.3 Writing test Classes

public class MyTest01 { @Test public void test01(){ String config="applicationContext.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(config); Student Student = (Student) ctx.getBean("myStudent"); System.out.println("student="+student); }}Copy the code

7.4 Use of Other Notes Value

Attribute: value is a String that represents the value position of a simple type attribute: 1. On property definitions, the set method is not required and is recommended. 2. To use the value of the external property profile above the set method, add a load property profile to the Spring configuration file.

<context:property-placeholder location="classpath:test.properties" />
Copy the code

7.4.1 Examples of Annotating Value:

@Component("myStudent") public class Student {/** * @value: simple type attribute assignment * attribute: String, indicating simple type attribute Value * position: 1. On property definitions, the set method is not required and is recommended. */ / @value ("${myname}") @value ("${myname}") private String name; @value ("${myage}") private Integer age; Public Student() {system.out.println ("== Student no argument constructor ==="); } public void setName(String name) { this.name = name; } //@Value("30") public void setAge(Integer age) { System.out.println("setAge:"+age); this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code

8. Annotation-based DI

8.1 The Spring framework provides annotations called Autowired

Autowired: Annotation provided by the Spring framework to implement assignment of reference types. Spring assigns values to reference types through annotations, using the principle of automatic injection. ByName is supported, byType@autowired: byType automatic injection is used by default. Location: 1) above the property definition, no set method is required, 2) above the set method is recommendedCopy the code

The byName of 8.1.1 Autowired

To use the byName method, you need to do the following: 1. Add @autoWired 2 to the attribute. Add @qualifier (value="bean ID ") above the attribute: indicates that assignment is completed using the bean with the specified name.Copy the code

8.1.2 Autowired required

Attribute: required, which is a Boolean. Default true required=true: indicates that the reference type assignment failed, the program reported an error, and execution was terminated. Required =false: Reference type If assignment fails, the program executes normally, and the reference type is NULLCopy the code

Resource annotations provided in the 8.1.3 JDK

Reference type @Resource: an annotation from the JDK. The Spring framework provides support for this annotation. You can use it to assign values to reference types using the automatic injection principle. The default byName position is: 1. Above the attribute definition, the set method is not required. If byName fails to be assigned, use byType@resource only byName. Add a name attribute to the bean id (name). For example: ByType @resource (name = "mySchool") private School School;Copy the code

JDK dynamic proxy

Proxy is a common design pattern whose purpose is to provide other objects with a proxy to control access to an object. The proxy class is responsible for preprocessing messages for the delegate class, filtering and forwarding messages, and for subsequent processing of messages after they are executed by the delegate class.

Code examples:

9.1 Service Interfaces

public interface SomeService {
    void doSome(a);
}
Copy the code

9.2 Service Interface Implementation Classes

public class SomeServiceImpl implements SomeService {
    @Override
    public void doSome(a) {
        System.out.println("Execute business method doSome"); }}Copy the code

9.3 Non-business tool Classes

public class ServiceTools {

    public static void doLog(a){
        System.out.println("Method execution time:"+ new Date());
    }

    public static void doTrans(a){
        // At the end of the method, commit the transaction
        System.out.println("Commit transaction after method completes execution"); }}Copy the code

9.4 InvocationHandler Implementation Classes (emphasis)

public class MyIncationHandler implements InvocationHandler {

    // Target object
    private Object target; / / SomeServiceImpl class

    public MyIncationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Invoke () is invoked when a method is executed through a proxy object
        Object res = null;
        ServiceTools.doLog(); // Outputs the time before the target method
        // Execute the Method of the target class, via the Method class
        res = method.invoke(target, args); //SomeServiceImpl.doSome()
        ServiceTools.doTrans(); // Commit the transaction after the target method executes
        // The execution result of the target method
        returnres; }}Copy the code

9.5 the test class

public class MyApp {
    public static void main(String[] args) {
        // Use JDK Proxy to create Proxy objects
        1. Create a target object
        SomeService target = new SomeServiceImpl();

        //2. Create InvocationHandler
        InvocationHandler handler = new MyIncationHandler(target);

        //3. Create a Proxy using Proxy
        SomeService proxy = (SomeService) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),handler);
        // Invoke () from handler when executing a method through a proxyproxy.doSome(); }}Copy the code

10.Aspectj AOP implementation

AOP (Aspect Orient Programming), section-oriented Programming. Section-oriented programming is considered from a dynamic perspective

Sequence running process. AOP bottom layer, is the implementation of dynamic proxy mode. Two types of proxies are used: JDK dynamic proxies, and CGLIB dynamic proxies. AOP for the abbreviation of Aspect Oriented Programming, meaning: section-oriented Programming, can achieve unified maintenance of program functions through run-time dynamic proxy technology. AOP is an important part of the Spring framework. Using AOP, each part of the business logic can be isolated, thus reducing the degree of coupling between each part of the business logic, improving the reusability of the program, and improving the efficiency of development.

10.1 Aspectj Maven dependencies added

AOP is a programming idea that has been implemented in many frameworks. Spring is one of them and can do orientation

Faceted programming. However, AspectJ also implements the functionality of AOP in a simpler, more user-friendly way, and supports annotated development. As a result, Spring has incorporated AspectJ’s implementation of AOP into its framework. When developing with AOP in Spring, AspectJ’s implementation is generally used.

Aspectj Maven dependencies added
    <! -- aspectj dependence - >
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.5. RELEASE</version>
    </dependency>
Copy the code

10.2 Introduction to Aspectj

10.2.1 Aspect

Aspect generally refers to the intersection of business logic. For example, transaction processing and logging can be understood as aspects. Commonly used cuts

It’s Advice. In effect, it is an enhancement to the main business logic. In simple terms: facets are new features to be added, enhancements to be made

10.2.2 Connecting Points (JoinPoint)

Join points refer to specific methods that can be woven into the cut surface. In general, methods in a business interface are join points.

10.2.3 Pointcut (== Key grasp ==)

A pointcut is a collection of one or more join points that are declared. A pointcut specifies a set of methods.

Methods marked as final are not join points and pointcuts. Because the ultimate is something that can’t be modified, it can’t be enhanced.

AspectJ defines special expressions for specifying pointcuts. The prototype for this expression is: Execution (modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) Explanation: Access permission Type RET-type-pattern Return value type variable -type-pattern Package name Class name name-pattern(param-pattern) Method name (parameter type and number of parameters) Throws the exception type? Represents optional partsCopy the code

The execution of a pointcut is mandatory, as is the return value of a symbolic notation and the method declaration (parameter)

Pointcut expressions can use special symbols to represent special operations, as shown below
symbol meaning
  • | 0 up to any character

.. | in the method parameter, says any more parameters. Used in the package name to represent the current package and its subpackages

  • | use behind the name of the class, said the current class and its subclasses. Used in an interface to represent the current interface and its implementation class

10.2.4 Target (Target)

The object object is the object to be enhanced. That is, the object of the class that contains the main karma logic.

10.2.5 Advice

Advice indicates the execution time of the aspect. Advice is also called enhancement. On the other hand, advice defines the point in time at which the enhancement code enters the object code, whether it is executed before or after the target method executes. Different notification types, different entry time.

Pointcuts define where to cut and inform the definition when to cut.

10.3 Five notification types commonly used by AspectJ

10.3.1Before: Pre-notification notes

Execute before the target method executes. Methods annotated as pre-notification can contain a JoinPoint type parameter

The number. Objects of this type are themselves pointcut expressions. With this parameter, you can obtain pointcut expressions, method signatures, target objects, and so on. Not only the pre-notification method can contain a JoinPoint type parameter, but all notification methods can contain this parameter.

The sample
/ * * *@Aspect: is an annotation in the AspectJ framework. * Function: Indicates that the current class is a facet class. * Aspect class: a class used to add functionality to business methods. In this class, there is the aspect function code * location: above the class definition */
@Aspect
public class MyAspect {
    /** * defines methods that implement the aspect function. Method definition requirements: * 1. Public method public * 2. Method has no return value * 3. Method name is custom * 4. Methods can have arguments or no arguments. * If there are parameters, the parameters are not custom and several parameter types can be used. * /


    / * * *@BeforeThe: pre-notification annotation * property: value is a pointcut expression that indicates where the function of the aspect is executed. * Position: above the method * Features: * 1. * 2 executed before the target method. Does not change the execution result of the target method * 3. Does not affect the execution of the target method. * /
    /** * Specifies the parameters in the notification method: JoinPoint * JoinPoint: specifies the parameters in the notification method: JoinPoint * specifies the parameters in the notification method. * If you need to use method information in the section function, add JoinPoint. * The JoinPoint parameter value is given by the framework and must be the first parameter */
    @Before(value = "execution(void *.. SomeServiceImpl.doSome(String,Integer))")
    public void myBefore(JoinPoint jp){
        // Get the full definition of the method
        System.out.println("Method signature (definition) ="+jp.getSignature());
        System.out.println("Method name ="+jp.getSignature().getName());
        // Get the argument to the method
        Object args [] = jp.getArgs();
        for (Object arg:args){
            System.out.println("Parameter ="+arg); }}}Copy the code
10.3.2 AfterReturning: Post notification

Execute after the target method executes. Since it is executed after the target method, the return value of the target method can be retrieved. The RETURNING attribute of the annotation is the name of the variable used to specify the value returned by the receiving method. So, a method annotated as a post-notification can contain, in addition to the JoinPoint argument, a variable used to receive the return value. This variable is best of type Object, because the return value of the target method can be of any type.

The sample

/ * * *@Aspect: is an annotation in the AspectJ framework. * Function: Indicates that the current class is a facet class. * Aspect class: a class used to add functionality to business methods. In this class, there is the aspect function code * location: above the class definition */
@Aspect
public class MyAspect {
    /** * Post-notification defines methods that implement the aspect function. Method definition requirements: * 1. Public method public * 2. Method has no return value * 3. Custom method name * 4. If the method has parameters, Object and custom parameter name */ are recommended

    / * * *@AfterReturningValue pointcut expression * 2. Returning custom variables representing the return value of the target method. * The custom variable name must be the same as the parameter name of the notification method. * Location: above the method definition * Features: * 1. Executed after the target method. Object res = doOther(); * 3. You can modify the return value * * after the execution of the notification * Object res = doOther(); MyAfterReturing (res); myAfterReturing(res); * System.out.println("res="+res) * */
    @AfterReturning(value = "execution(* *.. SomeServiceImpl.doOther(..) )", returning = "res")
    public void myAfterReturing( JoinPoint jp ,Object res ){
        // Object res: is the return value of the target method after execution
        System.out.println("Postnotification: Method Definition"+ jp.getSignature());
        System.out.println("Postnotification: Executed after the target method and returns:"+res); }}Copy the code
10.3.3 Around: Notification Around

Execute before and after the target method executes. Methods annotated as surround enhanced should have a return value of type Object. and

And the method can contain a parameter of type ProceedingJoinPoint. The ProceedingJoinPoint interface has a proceed() method that executes the target method. If the target method has a return value, that method’s return value is the target method’s return value. Finally, the wrap enhancement method returns its return value. The enhanced method actually intercepts the execution of the target method.

The sample
@Aspect
public class MyAspect {
    /** * Define the format around the notification method * 1.public * 2. There must be a return value, Object * 3 is recommended. Custom method name * 4. The method has parameters, and the fixed parameter ProceedingJoinPoint */

    / * * *@Around: Surround notification * Property: value pointcut expression * location: what is defined in the method * features: * 1. It is the most powerful notification * 2. Enhancements can be made before and after the target method. * 3. Control whether the target method is called to execute * 4. Modify the original target method execution result. The InvocationHandler interface parameter (*), which is equivalent to the JDK dynamic proxy, ProceedingJoinPoint ProceedingJoinPoint, returns the return value of the target Method. Is the result of the execution of the target method, which can be modified. * * Circular notification: Do transactions frequently, open transactions before target methods, execute target methods, commit transactions after target methods */
    @Around(value = "execution(* *.. SomeServiceImpl.doFirst(..) )"
    public Object myAround(ProceedingJoinPoint pjp) throws Throwable {

        String name = "";
        // Get the value of the first argument
        Object args [] = pjp.getArgs();
        if( args! =null && args.length > 1){
              Object arg=  args[0];
              name =(String)arg;
        }

        // Implement circular notification
        Object result = null;
        System.out.println("Surround notification: output time before target method:"+ new Date());
        //1. Target method call
        if( "zhangsan".equals(name)){
            // If the condition is met, call the target method
            result = pjp.proceed(); //method.invoke(); Object result = doFirst();

        }

        System.out.println("Surround notification: Commit transaction after target method");
        //2. Add functionality before or after the target method

        // Modify the execution result of the target method to affect the result of the last call to the method
        if( result ! =null){
              result = "Hello AspectJ AOP";
        }

        // Returns the execution result of the target method
        returnresult; }}Copy the code
10.3.4AfterThrowing: Exception notification

Executes after the target method throws an exception. The Throwing attribute of the annotation is used to specify the exception class object that occurred.

Of course, methods annotated as exception notifications can include a parameter Throwable, named as Throwing, which represents the exception object that occurred.

The sample
@Aspect
public class MyAspect {
    /** * Exception notification method definition format * 1.public * 2. No return value * 3. Method name custom * 4. Method has an Exception, if there is JoinPoint, */

    / * * *@AfterThrowing: Exception notification * Properties: 1. value pointcut expression * 2. Throwinng custom variable representing the exception object thrown by the target method. * The variable name must be the same as the method's parameter name. * Features: * 1. Can do exception monitoring program, monitoring the target method execution is not an exception. * try{* SomeServiceImpl. DoSecond (..) * }catch(Exception e){ * myAfterThrowing(e); *} * /
    @AfterThrowing(value = "execution(* *.. SomeServiceImpl.doSecond(..) )", throwing = "ex")
    public void myAfterThrowing(Exception ex) {
        System.out.println("Exception notification: When a method exception occurs, execute:"+ex.getMessage());
        // Send email, SMS, notification to developers}}Copy the code
10.3.5After: Final notification

This enhancement is executed whether or not the target method throws an exception.

The sample
@Aspect
public class MyAspect {
    /** * Final notification method definition format * 1.public * 2. No return value * 3. Method name custom * 4. Method has no parameters, if there is JoinPoint, */

    / * * *@After: Final notification * Property: value Pointcut expression * location: above method * Features: * 1. Always execute * 2. * * try{* someserviceimpl.dothird (..) * }catch(Exception e){ * * }finally{ * myAfter() * } * */
    @After(value = "execution(* *.. SomeServiceImpl.doThird(..) )"
    public  void  myAfter(a){
        System.out.println("Execute the final notification, always execute the code.");
        // Do the resource cleanup.}}Copy the code
10.3.6 Pointcut Defines a Pointcut

When more notification enhancement methods use the same execution pointcut expression, it can be cumbersome to write and maintain.

AspectJ provides the @Pointcut annotation to define an execution Pointcut expression. This is done by annotating @pointcut on top of a method so that all subsequent execution value attributes can use that method name as a Pointcut. Represents the Pointcut defined by @pointcut. This method with the @pointcut annotation generally uses the private identification method, which has no real effect.

The sample
@Aspect
public class MyAspect {


    @After(value = "mypt()")
    public  void  myAfter(a){
        System.out.println("Execute the final notification, always execute the code.");
        // Do the resource cleanup.
     }

    @Before(value = "mypt()")
    public  void  myBefore(a){
        System.out.println("Pre-notification, executed before target method.");
    }

    / * * *@Pointcut: Defines and manages pointcuts, which can be reused if more than one pointcut expression is repeated in your project. * Available@Pointcut* Attribute: value Pointcut expression * Position: above custom methods * Features: * when used@PointcutDefined above a method whose name is the alias of the pointcut expression. * In other advice, the value property can use the method name instead of the pointcut expression */
    @Pointcut(value = "execution(* *.. SomeServiceImpl.doThird(..) )"
    private void mypt(a){
        // No need for code,
    }

Copy the code

10.4 Implement AOP code complete flow using AspectJ

10.4.1 Importing Maven Dependencies

    <! - spring dependent - >
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5. RELEASE</version>
    </dependency>
    <! -- aspectj dependence - >
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.5. RELEASE</version>
    </dependency>

Copy the code

10.4.2 Defining service Interfaces and Implementation classes

Interface:

public interface SomeService {
    void doSome(String name,Integer age);
}

Copy the code

Implementation class:

/ / the target class
public class SomeServiceImpl implements SomeService {
    @Override
    public void doSome(String name,Integer age) {
        // Add a function to the doSome method to print the execution time of the method before doSome() is executed
        System.out.println("==== Target method doSome()===="); }}Copy the code

10.4.3 Defining the Aspect class

@Aspect
public class MyAspect {
    
    @Before(value = "execution(void *.. SomeServiceImpl.doSome(String,Integer))")
    public void myBefore(JoinPoint jp)
        // This is the function code that you want to implement}}Copy the code

10.4.4 Declaring the Target Object Section Class Object

Configure in the Spring configuration file:


    <! The spring container creates the object and manages it.
    <! Declare target object -->
    <bean id="someService" class="com.test.ba01.SomeServiceImpl" />
    <! Declare the section class object -->
    <bean id="myAspect" class="com.test.ba01.MyAspect" />
Copy the code

10.4.5 Registering AspectJ’s automatic proxy

Configure in the Spring configuration file:

    <! Declare automatic proxy generator: Creates proxy objects for target objects using functionality within the AspectJ framework. Creating the proxy object is done in memory, modifying the in-memory structure of the target object. Aspectj-autoproxy: Generates proxy objects for all target objects in the Spring container at once. -->
    <aop:aspectj-autoproxy />
Copy the code

11. Implementation of Spring transactions

Continuous updates…