Spring 5 latest complete teaching IDEA

catalogue

1,Spring

1.1 INTRODUCTION

1.2 advantages

1.3 composition

1.4 expansion

2. IOC theoretical derivation

2.1 essence of IOC

3,HelloSpring

3.1. Write a Hello entity class

3.2. Write our spring file, where we name beans.xml

3.3 instantiation container

4. How IOC creates objects

4.1. Create an object using parameterless construction, which is implemented by default

4.2. Suppose we want to use the parametric construction method to create objects

5. spring configuration

5.1 alias

5.2 Bean configuration

5.3,import

6. DI dependency injection

6.1. Constructor injection

6.3 expansion mode

6.4 scope of bean

7. Automatic assembly of Bean

7.1 test

7.2 ByName automatic assembly

7.3 ByType automatic assembly

7.4 automatic assembly

@Autowired

@Resource annotation

8. Using annotation development

1.bean

2. How to inject attributes

3. Derived notes

4. Automatic assembly

5. Scope

6. Summary

9. Configuring Spring in java

10. Agent mode

10.1 static agent

10.2 deepen understanding

10.3 dynamic agent

11.AOP

11.1 what is AOP

11.2. The role of AOP in Spring

11.3. Using Spring to implement APP

1,Spring

1.1 INTRODUCTION

  • Spring: Spring ----- > brings spring to the software industry!

  • In 2002, the prototype of Spring framework, interface 21, was launched for the first time

  • Spring framework is based on interface21 framework. After redesign and constantly enriching its connotation, it released the official version of 1.0 on March 24, 2004.

  • Rod Jahnson, founder and famous author of Spring Framework, doctor of University of Sydney, majoring in musicology.

  • Spring concept: make the existing technology easier to use. It is a hodgepodge and integrates the existing technology framework!

  • SSH: Struct2 + Spring + Hibernate

  • SSM: SpringMVC + Spring + Mybatis

    Official website: Spring Framework

    Gitub: GitHub - spring-projects/spring-framework: Spring Framework

    Official download address: JFrogJFrog JFrog

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.12</version>
</dependency>

1.2 advantages

  • Spring is an open source free framework (container)!

  • Spring is a lightweight, non intrusive framework!

  • Inversion of control (IOC), facing section (AOP)

  • Support transaction processing, which is the support for framework integration!

To sum up: Spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework

1.3 composition

1.4 expansion

There is this introduction on Spring's official website: Modern java development! To put it bluntly, it is the development of Spring

  • Spring Boot

    • A rapid development of scaffolding.

    • Based on SpringBoot, you can quickly develop a single microservice.

    • Agreement is greater than configuration!

  • Spring Cloud

    • Spring cloud is implemented based on SpringBoot

Because most companies are using SpringBoot for rapid development. To learn the premise of SpringBoot, you need to fully master Spring, Spring and Spring MVC! Show the role of up and down!

Disadvantages: after developing for too long, it violates the original concept! Configuration is very cumbersome, known as "configuration hell"

2. IOC theoretical derivation

2.1 essence of IOC

1.UserDao interface

2.USerDaolmpl implementation class

3.UserService business interface

4.UserServicelmpl business implementation class

We use a Set interface. Revolutionary changes have taken place

private UserDao ;
//Use set to dynamically realize the input of value!
public  void setUserDao(UserDao userDao){
    this.userDao=userDao;
}

  • Before, the program was actively creating objects! Control is in the hands of programmers!

  • After using set injection, the program no longer has the initiative, but becomes a passive receiving object!

  • This idea essentially solves the problem. We programmers don't have to manage the creation of objects.

    Inversion of control is a design idea. DI(dependency injection) is a method of IOC. In programs that do not use IOC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded in the program, The creation of objects is controlled by the program itself. Control inversion is to transfer the creation of objects to a third party. IOC, I think, is that the way to obtain dependent objects is reversed

    IOC is the core content of the spring framework. It uses a variety of ways to perfectly implement IOC in the form of XML configuration and annotation. The new version of spring can also implement IOC with zero configuration

3,HelloSpring

Project structure

Note: spring needs to import commons logging for logging. We use maven, which will automatically help us download the corresponding dependencies and configure them in pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.12</version>
</dependency>

3.1. Write a Hello entity class

package com.kang.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

3.2. Write our spring file, where we name beans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    use Spring To create an object, in Spring These have become Bean
        Type variable name  =  new type();
        Hello hello= new Hello();
        bean = object new  Hello();

        id = Variable name
        class = new Object of
        property This is equivalent to setting a value for the genus in the object

-->
            <bean id="hello" class="com.kang.pojo.Hello">
            <property name="str" value="Spring"></property>
        </bean>
</beans>

3.3 instantiation container

import com.kang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​public class MyText {   
 public static void main(String[] args) { 
       //Get Spring context object      
       ApplicationContext content=new ClassPathXmlApplicationContext("beans.xml");     
       //Our objects are now managed in Spring. We need to use them. Just take them out directly!     
       Hello hello = (Hello) content.getBean("hello");
       System.out.println(hello.toString()); 
   }
}​


​

4. How IOC creates objects

4.1. Create an object using parameterless construction, which is implemented by default

public class User {
    private String name;
    public User(){

    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name="+name);
    }
}
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--    use Spring To create an object, in Spring These have become Bean
            Type variable name  =  new type();
            Hello hello= new Hello();
            bean = object new  Hello();

            id = Variable name
            class = new Object of
            property This is equivalent to setting a value for the genus in the object

    -->
    <bean id="user" class="com.kang.pojo.User">
        <property name="name" value="Kang"></property>
    </bean>
</beans>

4.2. Suppose we want to use the parametric construction method to create objects

public User(String name){
	this.name=name;
}

1. Subscript assignment

 <bean id="user" class="com.kang.pojo.User">
        <constructor-arg index="0" value="Kangzi"></constructor-arg>
    </bean>

2. Create by type. If there are two same types, it will not work. It is not recommended

<bean id="user" class="com.kang.pojo.User">
        <constructor-arg type="java.lang.String" value="kang"></constructor-arg>
    </bean>

3. Set directly by parameter name

 <bean id="user" class="com.kang.pojo.User">
        <constructor-arg name="name" value="Kangzi"></constructor-arg>
    </bean>

Project structure

Summary: when the configuration file is loaded, the objects managed in the container have been initialized!

5. spring configuration

5.1 alias

<!--    Alias. If an alias is added, we can also use the alias to get this object-->
    <alias name="user" alias="newuswe"></alias>

5.2 Bean configuration

    <!--
id: bean The unique identifier of, that is, the object name equivalent to the variable name we learned
class: bean Fully qualified name corresponding to the object: package name+type
name: It's also an alias, and name More advanced
​-->
    <bean id="usert" class="com.kang.pojo.UserT" name="user2 u2,u3;u4">
        <property name="name" value="Pudding"></property>
    </bean>
<!--    Alias. If an alias is added, we can also use the alias to get this object-->
    <alias name="user" alias="newuswe"></alias>
</beans>

5.3,import

This import is generally used for team development. It can import and merge multiple configuration files into one

Suppose there are multiple developers in the project. These three developers copy different classes for development. Different classes need to be registered in different bean s. We can use them

import merges everyone's beans.xml into a total

  • Zhang San

  • Li Si

  • Wang Wu

  • applicationContext.xml

        <import resource="beans.xml"/>
        <import resource="beans1.xml"/>
        <import resource="beans2.xml"/>

    The same content will also be merged

When using, just use the general configuration directly

6. DI dependency injection

6.1. Constructor injection

6.2. Inject [ key ]

  • Dependency injection: the essence is set injection!

    • Dependency: the creation of bean objects depends on the container

    • Injection: all the attributes of the bean object are injected by the container!

[environment construction]

  1. Complex type

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
     @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}

2. Real test object

public class Stutent {
    private  String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife; 
    private Properties info;
}

3.applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="student" class="com.kang.pojo.Stutent">
        <!--The first is ordinary value injection, which is used directly value -->
        <property name="name" value="Wen Kang"></property>
    </bean>
</beans>

4. Testing

public class MyText {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Stutent student = (Stutent) context.getBean("student");

        System.out.println(student.getName());
    }
}

5. Improve injection

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.kang.pojo.Address" >
        <property name="address" value="Shandong Province"></property>
    </bean>

    <bean id="student" class="com.kang.pojo.Stutent">
        <!--The first is ordinary value injection, which is used directly value -->
        <property name="name" value="Wenzi"/>
        <!--The second injection, Bean Injection, use ref injection -->
        <property name="address" ref="address"/>
        <!--Third, array injection -->
        <property name="books">
            <array>
                <value>The Dream of Red Mansion</value>
                <value>Journey to the West</value>
                <value>Water Margin</value>
            </array>
        </property>
        <!--List injection  -->
        <property name="hobbys">
            <list>
                <value>learn java</value>
                <value>Type code</value>
                <value>see java teaching</value>
            </list>
        </property>
        <!--Map injection -->
        <property name="card">
            <map>
                <entry key="ID" value="375326200108022526"/>
                <entry key="bank card" value="6753266001080252622"/>
            </map>
        </property>
        <!--Set injection -->
        <property name="games">
            <set>
                <value>Glory of Kings</value>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>
        <!--Null injection null  -->
        <property name="wife">
           <null/>
        </property>
        <!-- Properties injection-->
        <property name="info">
            <props>
                <prop key="driver">183350</prop>
                <prop key="class">18 class</prop>
            </props>
        </property>
    </bean>
</beans> 

6. Improve testing

public class MyText {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Stutent student = (Stutent) context.getBean("student");

        System.out.println(student.toString());
/*
*Stutent{name='Wen Zi ',
*   address=Address{address='Shandong Province '},,
*   books=[Dream of Red Mansions, journey to the west, outlaws of the marsh],
*   hobbys=[Learn java, type code, watch java Teaching],
*   card={
*       ID card = 375326200108022526,
*       Bank card = 6753266001z080252622
*   },
*   games=[Glory of the king, LOL, COC],
*   wife='null',
*   info={
*       driver=183350,
*       class=18 class
*   }
* }
* */
    }
}

6.3 expansion mode

We can use the p namespace and the c namespace for injection

2. Use

Import the namespace in applicationContext.xml first

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--p Namespace injection, you can directly inject attribute values: property    -->
    <bean id="user" class="com.kang.pojo.User" p:name="Wen Kang" p:age="18" />

        <!--c Namespace injection, which can be injected through the constructor: constructs     -->
    <bean id="user2" class="com.kang.pojo.User" c:age="18" c:name="Kangzi" />
</beans>

3. Test

 @Test
    public void test2(){
       ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
        User user =  context.getBean("user2",User.class);
        System.out.println(user);

    }

Note: the p naming and c namespace cannot be used directly. You need to import xml constraints!

  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:c="http://www.springframework.org/schema/c"

6.4 scope of bean

1.1 singleton mode

singleton scope means that in the whole Spring container, a bean definition only generates a unique bean instance, which is managed by the Spring container. All requests and references to this bean will return the bean instance.

The following figure illustrates how the singleton scope works:

In the figure above, this bean is referenced in three places, and all three references refer to the same bean instance.

1.1 singleton scope is the default scope in Spring. You can specify it or not when defining bean s, as follows:

<!-- No scope is specified. The default is singleton -->
<bean id="user2" class="com.kang.pojo.User" c:age="18" c:name="Pudding" />

<!-- Displays the specified scope as singleton -->
<bean id="user2" class="com.kang.pojo.User" c:age="18" c:name="Pudding" scope="session" />

2 prototype mode prototype ` scope

Each time you get from the container, a new object is generated

1.2 prototype scope

The prototype scope indicates that a bean definition can create multiple bean instances, which is a bit like a class can new multiple instances.

That is, a new bean instance will be generated when it is injected into other beans or when getBean() is called on this bean definition.

As a rule, you should specify the prototype scope for all stateful beans and the singleton scope for all stateless beans.

The following figure describes how the prototype scope works:

In the figure above, each reference corresponds to a new bean instance.

Note that the example above does not apply to production environments. Because DAO is usually a stateless bean, it is appropriate to specify its scope as singleton.

The prototype scope can be defined in xml as follows:

<bean id="user2" class="com.kang.pojo.User" c:age="18" c:name="Pudding" scope="prototype" />

3. Other request, session, application and websocket scopes

request, session, application and websocket scopes are only useful in the web environment.

7. Automatic assembly of Bean

Before talking about automatic assembly, let's talk about manual assembly.

Manual assembly is what we talked about earlier. You should give your own attributes and then assign values

  • Automatic assembly is a way for spring to meet bean dependencies!

  • Spring will automatically find in the context and automatically assemble properties for the bean!

  • There are three ways to assemble in Spring

    1. Configuration displayed in xml

    2. Display configuration in java

    3. Implicit auto assembly bean [important]

automatic assembly

When a Bean has few properties, we use few < constructor Arg > or < property > elements for assembly when configuring it. However, with the increase of the project volume, the Bean may also become complex. At this time, the configuration file will also become complex. There will be a lot of < constructor Arg > and < property > and it will be difficult to write, Fortunately, Spring provides us with an automatic assembly mechanism. autowire mode

The Spring IOC container can assemble beans automatically. You only need to specify the assembly mode in the autowire attribute of < Bean >.

7.1 test

Environment construction: a person has two pets

7.2 ByName automatic assembly

<!--  byName Principle: it will automatically find and own objects in the container context set Method beanid!  -->
<bean id="people" class="com.kang.pojo.People" autowire="byName">
    <property name="name" value="Pudding"/>
</bean>

7.3 ByType automatic assembly

<!--  byType Principle: it will automatically find the object with the same attribute type as its own object in the container context bean    !  -->
<bean id="people" class="com.kang.pojo.People" autowire="byType">
    <property name="name" value="Pudding"/>
</bean>

Summary:

  • byName, you need to ensure that the IDs of all beans are unique, and the bean needs to be consistent with the value of the set method of the automatically injected attribute

  • When byType, it is necessary to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of automatically injected properties

7.4 automatic assembly

The introduction of annotation-based configuration raised the question of whether this approach is "better" than XML.

Notes to use notes

  1. Import constraints: context constraints

  2. Support for configuration annotation: Context: annotation config / [key]

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

    @Autowired

    It can be used directly on attributes or in set mode

    Using Autowired, we don't need to write a set method. Your auto assembled attribute exists in the IOC (Spring) container and conforms to our name

    byname!

    polular science:

    @The Nullable field marks this annotation, indicating that this field can be null

    Test code

     //If the required attribute of Autowired is false, it indicates that the object can be Noll, otherwise it is not allowed to be empty
        @Autowired
        private Cat cat;
        @Autowired
        private Dog dog;
        private String name;
    }
     

    If the environment of @ Autowired automatic assembly is complex and the automatic assembly cannot be completed through an annotation [@ Autowired], we can

    Use @ Oualifier (value="xxx") to configure the use of Autowired and specify a unique bean object to use

    //If the required attribute of Autowired is false, it indicates that the object can be Noll, otherwise it is not allowed to be empty
        @Autowired
        @Oualifier(value="cat111")
        private Cat cat;
        @Autowired
        @Oualifier(value="dog111")
        private Dog dog;
        private String name;
    
     <bean id="cat111" class="com.kang.pojo.Cat"/>
     <bean id="dog111" class="com.kang.pojo.Dog"/>

    @Resource annotation

public class People {
	@Resouce(name="cat2")
    private Cat cat;
	@Resouce
    private Dog dog;

}

Summary:

@Difference between Resouce and @ Autowired:

  • They are used for automatic assembly and can be placed in the attribute field

  • @Autowired: implemented by byType, and this object must exist!

  • @Resouce: by default, it is implemented by byname. If the name cannot be found, it is implemented by byType. If both cannot be found, an error will be reported!

  • Different execution order: annotation description

    • @Autowired: auto assembly type, name

      • If Autowired cannot uniquely auto assemble attributes, you need to pass @ Oualifier (value="xxx")

    • @Resouce: name and type of automatic assembly

8. Using annotation development

After spring 4, if you want to develop with annotations, you must ensure that the aop package is imported

To use annotations, you need to import content constraints and add annotation support

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd
   ">

</beans>

1.bean

2. How to inject attributes

//Component is equivalent to < bean id = "user" class = "com. Kang. POJO. User" / >
//English name component
@Component
public class User {
    //Equivalent to < property name = "name" value = "pudding" / >
    @Value("Pudding")
    public String name;

}

3. Derived notes

@Component has several derived annotations. In web development, we will layer according to mvc three-tier architecture!

  • dao[@Repository ]

  • service[@Service ]

  • controller[@Controller]

    These four annotation functions are the same. They all represent registering a class in the Spring container and assembling beans!

4. Automatic assembly

- @Autowired: Auto assembly type, name
  - If Autowired If the attribute cannot be uniquely auto assembled, you need to pass the@Oualifier(value="xxx")
- @Resouce: Automatic assembly by name, type
- @Nullable  Field is marked with this annotation, indicating that this field can be null

5. Scope

@Component
@Scope("singleton")
public class User {
    //Equivalent to < property name = "name" value = "pudding" / >
    @Value("Pudding")
    public String name;

}

6. Summary

xml and annotations:

  • xml is more versatile and suitable for any scene! Simple and convenient maintenance

  • Annotation: annotations are not their own classes and cannot be used. Maintenance is relatively complex!

Best practices for xml and annotations

  • xml is used to manage bean s;

  • Annotation is only responsible for completing attribute injection;

  • In the process of using, we only need to pay attention to one problem: if we must make the annotation effective, we must turn on the annotation support

  <!--  Specify the package to be scanned, and the annotations under the package will take effect  -->
    <context:component-scan base-package="com.kang"/>
    <!--  Annotation driven-->
    <context:annotation-config/>

9. Configuring Spring in java

Now we will not use the xml configuration of Spring at all, and leave it to java!

JavaConfig is a sub project of Spring. It has become a core function after Spring 4!

Entity class

//This annotation means that this class is taken over by Spring and registered in the container
@Controller
public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value("Pudding")//Attribute injection value
    public void setNmae(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "nmae='" + name + '\'' +
                '}';
    }
}

Profile class

package com.kang.config;

import com.kang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

//This will also be registered in the container by the Spring container, because it is a @ Controller,
// @Configuration represents this configuration class, which is the same as beans.xml we saw earlier
@Configuration
@ComponentScan("com.kang.pojo")
@Import(MyConfig2.class)
public class MyConfig {

    //Registering a bean is equivalent to a bean tag we wrote earlier
    //The name of this method is equivalent to the id attribute in the bean tag
    //The return value of this method is equivalent to the class attribute in the bean tag
    @Bean
    public User getuser(){
        return new User();//Is to return the object to be injected into the bean
    }
}

Profile 2

@Configuration
public class MyConfig2 {

}

Test class!

public class Mytext {
    public static void main(String[] args) {
        //If the configuration class method is completely used, we can only obtain the container through the AnnotationConfig context and load it through the class object of the configuration class
       ApplicationContext content = new AnnotationConfigApplicationContext(MyConfig.class);
        User getuser = content.getBean("getuser", User.class);
        System.out.println(getuser.getName());

    }
}

This pure java configuration can be seen everywhere in SpringBoot!

10. Agent mode

Why learn agent mode?

Because this is the bottom layer of spring AOP! [spring AOP and spring MVC]

Agent mode classification:

  • Static proxy

  • Dynamic agent

10.1 static agent

Role analysis:

  • Abstract role: generally use interface or interface class

  • True role: the role represented

  • Agent role: an agent is a real role. After representing a real role, we usually do some ancillary operations

  • Customer: the person who accesses the proxy object!

Code steps:

  1. Interface


```java
public interface Rent {
    public void rent();
}
```

2. Real role

//landlord or landlady
public class Host implements Rent{
    public void rent() {
        System.out.println("The landlord wants to rent a house");
    }
}

3. Agent role

//intermediary
public class Proxy  implements Rent{

    private Host host;


    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        host.rent();
        seeHouse();
        fare();
    }
    //House viewing
    public void seeHouse(){
        System.out.println("The agent will show you the house");
    }
    //Intermediary fee
    public void fare(){
        System.out.println("Intermediary fee");
    }
}

4. Client access agent role

public class Client {
    public static void main(String[] args) {
        Host host=new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

Benefits of agent mode:

  • It can make the operation of real characters more pure!

  • The public will be handed over to the agent role! Realize the division of business!

  • When public business is expanded, it is convenient for centralized management!

shortcoming

  • A real role will produce a proxy role; The amount of code will double and the development efficiency will be low

10.2 deepen understanding

10.3 dynamic agent

  • Dynamic agents have the same role as static agents

  • The agent class of dynamic agent is dynamically generated, which is not written directly by us!

  • Dynamic agents are divided into two categories: interface based dynamic agents and class based dynamic agents

    • Based on interface -- jdk dynamic agent [let's use jdk]

    • Class based: cglib

    • java bytecode implementation: javasist

Two classes need to be understood: Proxy: Proxy, and invocation: call handler

Benefits of dynamic agents:

  • It can make the operation of real characters more pure! Don't pay attention to some public business

  • The public will be handed over to the agent role! Realize the division of business!

  • When public business is expanded, it is convenient for centralized management!

  • A dynamic proxy class proxy interface is generally the corresponding business

  • A dynamic proxy class can proxy multiple classes as long as multiple classes are implemented

11.AOP

11.1 what is AOP

AOP (Aspect Oriented Programming) is the abbreviation of slice oriented programming. AOP is realized by precompiling and runtime dynamic agent. It is a technology to dynamically and uniformly add functions to programs without modifying the source code, which is called AOP for short. It is an important part of spring framework and a derivative model of OOP (object-oriented programming).

Role of AOP:

AOP is used to isolate each part of business logic, reduce the coupling of business logic, and improve the reusability and development efficiency of programs.

11.2. The role of AOP in Spring

Provide declarative transactions: allow users to customize aspects

  • Crosscutting concerns: methods or functions that span multiple modules of an application. It has nothing to do with our business logic, but the part we need to focus on is crosscutting concerns, such as logging, security, caching, transactions, etc

  • ASPECT: a special object whose crosscutting concerns are modularized. That is, it is a class.

  • Advice: work that must be completed in all aspects. That is, it is a method in a class.

  • Target: the notified object.

  • Proxy: an object created after notification is applied to the target object.

  • PointCut: the definition of the "place" where the aspect notification is executed.

  • Join point: the execution point that matches the pointcut.

In spring AOP, crosscutting logic is defined through Advice. Spring supports five types of Advice:

That is, Aop adds new functions without changing the original code

11.3. Using Spring to implement APP

[key] to use AOP weaving, you need to import a dependency package

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

Method 1: use the Spring API interface [mainly the Spring API interface implementation]

Method 2: use user-defined classes to implement AOP [mainly facets]

//Method 3: implement AOP by annotation
@Aspect//Label this class as a facet
public class AnnotionPointCut {

    @Before("execution(* com.kang.service.UserServiceImpl.*(..))")
    public void  before(){
        System.out.println("===== Before method execution======");
    }

    @After("execution(* com.kang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===== After method execution======");
    }

 
}

 

Tags: Java Maven Spring AOP ioc

Posted on Thu, 04 Nov 2021 03:29:03 -0400 by Anas_M.M.F