Spring learning notes [All]

Learn about Spring

Official website: https://spring.io/projects/spring-framework#learn

Official download address: https://repo.spring.io/ui/native/release/org/springframework/spring

GitHub: https://github.com/spring-projects/spring-framework

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


advantage

  • Spring is an open source free framework (container)

  • Spring is a lightweight, non intrusive framework

  • Inversion of control (IOC), aspect oriented programming (AOP)

  • Support transaction processing and framework integration

Spring is a lightweight framework for inversion of control (IOC) and aspect oriented programming (AOP)

form

How IOC creates objects

When the configuration file is loaded, the objects managed in the container have been initialized

Objects are created using parameterless construction by default

Methods of creating objects using parametric constructs

  1. Subscript assignment

    <bean id="user" class="com.lzj.entity.User">
    	<constructor-arg index="0" value="lzj"></constructor-arg>
    </bean>
    
  2. type assignment

    <bean id="user" class="com.lzj.entity.User">
    	<constructor-arg type="java.lang.String" value="lzj"></constructor-arg>
    </bean>
    
  3. By parameter name

    <bean id="user" class="com.lzj.entity.User">
    	<constructor-arg name="name" value="lzj"></constructor-arg>
    </bean>
    

Spring configuration

  1. alias

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

    <!--
    	id:bean The unique identifier of, which is equivalent to the object name we learned
    	class:bean Fully qualified name corresponding to the object: package name+type
    	name: It's also an alias, and name,Multiple aliases can be taken at the same time
    -->
    <bean id="userT" class="com.lzj.entity.UserT" name="u1,u2">
    	<property name="name" value="lzj"></property>
    </bean>
    
  3. import

    It is generally used for team development. Multiple configuration files can be imported and merged into one

    Suppose that there are multiple developers in the project. These three people are responsible for the development of different classes. Different classes need to be registered in different bean s. We can use import to transfer everyone's baens Merge XML into a total

    • applicationContext.xml
    <import resource="beans.xml"></import>
    <import resource="beans2.xml"></import>
    <import resource="beans3.xml"></import>
    

    When using, just use the general configuration directly

Dependency injection

Set mode injection

  • Dependency: the creation of bean objects depends on the container
  • Injection: all properties in 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 Student {
        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. Perfect injection information (xml configuration file)

    <?xml version="1.0" encoding="UTF-8"?>
    <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 http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="address" class="com.lzj.entity.Address">
        	<property name="address" value="Wuhan"></property>
        </bean>
        <bean id="student" class="com.lzj.entity.Student">
    <!--        First, normal value injection, value-->
            <property name="name" value="lzj"></property>
    <!--        Second, Bean Injection, ref-->
            <property name="address" ref="address"></property>
    <!--        array-->
            <property name="books">
                <array>
                    <value>The Dream of Red Mansion</value>
                    <value>Journey to the West</value>
                    <value>Water Margin</value>
                    <value>Romance of the Three Kingdoms</value>
                </array>
            </property>
    <!--        List-->
            <property name="hobbies">
                <list>
                    <value>listen to the music</value>
                    <value>Knock code</value>
                    <value>watch movie</value>
                </list>
            </property>
    <!--       Map -->
            <property name="card">
                <map>
                    <entry key="ID" value="2132132465456"></entry>
                    <entry key="bank card" value="546565432134"></entry>
                </map>
            </property>
    <!--        Set-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>COC</value>
                    <value>BOB</value>
                </set>
            </property>
    <!--        null-->
            <property name="wife">
                <null></null>
            </property>
    <!--        properties-->
            <property name="info">
                <props>
                    <prop key="Student number">20191025302</prop>
                    <prop key="Gender">male</prop>
                    <prop key="full name">lzj</prop>
                </props>
            </property>
        </bean>
    </beans>
    
  4. test

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            Student student = (Student) context.getBean("student");
            System.out.println(student);
        }
    }
    

p namespace and c namespace injection

p naming and c namespace cannot be used directly, and xml constraints need to be imported

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

Official document location:

use:

Entity class:

public class User {
    private String name;
    private int age;

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

    public User() {
    }
}

xml configuration file

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    p Namespace injection, you can directly inject the value of the attribute: property-->
    <bean id="user" class="com.lzj.entity.User" p:name="lzj" p:age="20"></bean>
<!--    c Namespace injection through constructor: construct-args-->
    <bean id="user2" class="com.lzj.entity.User" c:name="lzj" c:age="20"></bean>
</beans>

Test:

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

}

Scope of bean

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
  1. Singleton mode (Spring default mechanism)

    scope="singleton"

    <bean id="user2" class="com.lzj.entity.User" c:name="lzj" c:age="20" scope="singleton"></bean>
    
  2. Prototype pattern: every time you get from the container, a new object will be generated

    scope="prototype"

    <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
    
  3. The rest of the request, session, application and can only be used in web development

Automatic assembly of Bean

  • 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

byName auto assembly

All bean IDS need to be unique, and the bean needs to be consistent with the value of the set method of the automatically injected attribute

<bean id="cat" class="com.lzj.entity.Cat"></bean>
<bean id="dog" class="com.lzj.entity.Dog"></bean>
<!--
	byName: It will automatically find its own objects in the container context set The value after the method corresponds to beanid
-->
<bean id="people" class="com.lzj.entity.People" autowire="baName">
	<property name="name" value="lzj"></property>
</bean>

byType auto assembly

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 attributes

<bean id="cat" class="com.lzj.entity.Cat"></bean>
<bean id="dog2" class="com.lzj.entity.Dog"></bean>
<!--
	byName: It will automatically find the object with the same property type as its own object in the container context bean
-->
<bean id="people" class="com.lzj.entity.People" autowire="byType">
	<property name="name" value="lzj"></property>
</bean>

Automatic assembly using annotations

  1. Import constraint (context constraint)

    xmlns:context="http://www.springframework.org/schema/context"
    
    http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd
    
    <context:annotation-config/>
    
  2. Configuration annotation support: Context: annotation config / [!!!]

    <?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

You can use it directly on the attribute! It can also be used in set mode

Using Autowired, we don't need to write the Set method. The premise is that the attribute assembled automatically exists in the IOC (Spring) container and conforms to the name byType

If the environment of @ Autowired automatic assembly is complex and the automatic assembly cannot be completed through - annotation [@ Autowired], we can use @ Qualifier(value = "xx") to configure the use of @ Autowired and specify a unique bean object injection!

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}

@Resource annotation

  1. Import dependent

    <!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>javax.annotation-api</artifactId>
        <version>1.3.2</version>
    </dependency>
    
  2. Use annotations in entity classes

    public class People {
        @Resource
        private Cat cat;
        @Resource(name = "dog22")
        private Dog dog;
        private String name;
    }
    

difference

@Difference between Resource and @ Autowired:

  • They are used for automatic assembly and can be placed in the attribute field
  • @Autowired is implemented by byType. If it cannot be found by byType, the @ Qualifier annotation will be used. According to byName, this object must exist
  • @Resource is implemented by byName by default. If the name cannot be found, it is implemented by byType! If both cannot be found, report an error!
  • Execution order is different

Development using annotations

  1. bean

    1. Import the configuration file and specify the packages to scan

      <?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">
      
      <!--    Specify the package to be scanned, and the annotation under this package will take effect-->
          <context:component-scan base-package="com.lzj.entity"></context:component-scan>
          <context:annotation-config/>
      
      </beans>
      
    2. Entity class uses annotation (@ Component)

    //Equivalent to < bean id = "user" class = "com. LZJ. Entity. User" / >
    //@Component component
    @Component
    public class User {
        public String name;
    }
    
  2. How to inject attributes

    public class User {
        //Equivalent to < property name = "name" value = "LZJ" / >
        @Value("lzj")
        public String name;
    }
    
  3. Derived annotation

    @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 Spring and assembling beans

  4. Automatic installation configuration

    • @Autowired: auto assembly type. name

      If Autowired cannot uniquely auto assemble attributes, it needs to pass * * @ qualifier**(va1ue = "xxx")

    • @The Nullable field is marked with this annotation, indicating that this field can be null;

    • @Resource: name of automatic assembly. Type.

  5. Scope (@ scope)

    //Specifies that the scope is prototype mode
    @Scope("prototype")
    public class User {
        public String name;
    }
    
  6. Summary

    xml and annotations:

    • xml is more versatile and suitable for any occasion! Simple and convenient maintenance
    • Annotations are not their own classes and cannot be used. Maintenance is relatively complex!

    xml and annotation best practices:

    • 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 need to turn on the annotation support

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

Configure Spring in Java

Entity class

@Component
public class User {
    @Value(value = "lzj")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

configuration file

@Configuration
@ComponentScan("com.lzj.entity")//By default, all configuration classes under the package where this class is located will be scanned
@Import(LzjConfig2.class)
public class LzjConfig {
    //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 Fbean tag
    //The return value of this method is equivalent to the Klass attribute in the Fbean tag
    @Bean
    public User getUser(){
        return new User();//Is to return the object to be injected into the bean
    }
}

Test class

public class MyTest {
    public static void main(String[] args) {
        //. if the configuration class method is completely used, we can only do it through AnnotationConfig Context to get the container, and load it through the class object of the configuration class!
        ApplicationContext context = new AnnotationConfigApplicationContext(LzjConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

proxy pattern

Static proxy

Role analysis:

  • Abstract role: it is usually solved by using interfaces or abstract classes
  • Real role: the role represented
  • Acting role: acting as a real role. After acting as a real role, we usually do some ancillary operations
  • Client: the person who accesses the proxy object

Code steps:

  1. Interface

    //Rent a house
    public interface Rent {
        public void rent();
    }
    
  2. Real role

    //landlord or landlady
    public class Host implements Rent{
    
        @Override
        public void rent() {
            System.out.println("The landlord wants to rent out");
        }
    }
    
  3. delegable role

    //intermediary
    public class Proxy {
        private Host host;
    
        public Proxy() {
        }
    
        public Proxy(Host host) {
            this.host = host;
        }
        public void rent(){
            host.rent();
        }
    }
    
  4. Client access agent role

    //Someone who wants to rent a house
    public class Client {
        public static void main(String[] args) {
            Host host = new Host();
            Proxy proxy = new Proxy(host);
            proxy.rent();
    
        }
    }
    

Dynamic agent

  • Dynamic agents have the same role as static agents
  • The agent class of dynamic agent is generated dynamically, which is not written directly
  • Dynamic agents are divided into two categories: interface based dynamic agents and class based dynamic agents
    • Interface based - JDK dynamic agent
    • Based on class --------- cglib
    • Byte: vsja implementation

Code steps:

  1. Interface

    //Rent a house
    public interface Rent {
        public void rent();
    }
    
  2. Real role

    //landlord or landlady
    public class Host implements Rent{
    
        @Override
        public void rent() {
            System.out.println("The landlord wants to rent out");
        }
    }
    
  3. Create a class to automatically generate proxy classes

    //The way of this class can be universal
    public class ProxyInvocationHandler implements InvocationHandler {
        //Proxy interface
        private Object target;
    
        public void setTarget(Object target) {
            this.target = target;
        }
    
        //Generated proxy class
        public Object getProxy(){
            return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
        }
    
    
        //Process the proxy instance and return the result. Method is the method obtained through reflection
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(target, args);
            return result;
        }
    }
    
    
  4. Client access agent role

    //Someone who wants to rent a house
    public class Client {
        public static void main(String[] args) {
            //Real role
            Host host = new Host();
            //delegable role
            ProxyInvocationHandler pih = new ProxyInvocationHandler();
            //Handle the interface object we want to call by calling the program processing role
            pih.setTarget(host);
            //Dynamic proxy is the interface
            //Here, you need to forcibly convert to the type of interface rather than the type of implementation class
            Rent proxy = (Rent) pih.getProxy();
            proxy.rent();
        }
    }
    

AOP in Spring

The role of AOP in Spring

Provides declarative transactions that allow users to customize aspects

  • Crosscutting concerns: methods or functions that span multiple modules of an application. That is, the part that has nothing to do with our business logic, but we need to focus on is crosscutting concerns. Such as log, security, cache, transaction and so on
  • 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.

Using Spring's API to implement Aop

Code steps:

  1. Import dependency

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

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void select();
    }
    
  3. Implementation class

    public class UserServiceImpl implements UserService{
        @Override
        public void add() {
            System.out.println("Added a user");
        }
    
        @Override
        public void delete() {
            System.out.println("A user was deleted");
        }
    
        @Override
        public void update() {
            System.out.println("Updated a user");
        }
    
        @Override
        public void select() {
            System.out.println("Queried a user");
        }
    }
    
  4. Pre log

    public class Log implements MethodBeforeAdvice {
        //method of the object to execute
        //args: parameter
        //Target: target object
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println(target.getClass().getName()+"of"+method.getName()+"Executed");
        }
    }
    
  5. Post log

    public class AfterLog implements AfterReturningAdvice {
        //returnValue: return value
        @Override
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("Yes"+method.getName()+"The returned result is:"+returnValue);
        }
    }
    
  6. xml configuration

    You need to import xml constraints before

    <?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">
    
    <!--    register bean-->
        <bean id="userservice" class="com.lzj.service.UserServiceImpl"></bean>
        <bean id="log" class="com.lzj.log.Log"></bean>
        <bean id="afterlog" class="com.lzj.log.AfterLog"></bean>
    <!--to configure aop: Import required aop Constraints of-->
        <aop:config>
    <!--        Entry point: expression;expression, execution(Location to execute! * * * * *)-->
            <aop:pointcut id="pointcut" expression="execution(* com.lzj.service.UserServiceImpl.*(..))"/>
    <!--        Execute surround increase-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
            <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"></aop:advisor>
        </aop:config>
    </beans>
    
  7. test

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //Dynamic proxy is the interface
            UserService userservice = (UserService) context.getBean("userservice");
            userservice.add();
        }
    }
    

Custom implementation AOP

Compared with using the API implementation of Spring, Aop modifies the xml configuration file and replaces the pre log and post log with custom classes

Code steps:

  1. Import dependency

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

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void select();
    }
    
  3. Implementation class

    public class UserServiceImpl implements UserService{
        @Override
        public void add() {
            System.out.println("Added a user");
        }
    
        @Override
        public void delete() {
            System.out.println("A user was deleted");
        }
    
        @Override
        public void update() {
            System.out.println("Updated a user");
        }
    
        @Override
        public void select() {
            System.out.println("Queried a user");
        }
    }
    
  4. Custom class

    public class DiyPointCut {
        public void before(){
            System.out.println("=========Before method execution=========");
        }
        public void after(){
            System.out.println("=========After method execution=========");
        }
    
    }
    
  5. xml configuration

    You need to import xml constraints before

    <?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">
    
    <!--    register bean-->
        <bean id="userservice" class="com.lzj.service.UserServiceImpl"></bean>
        <bean id="log" class="com.lzj.log.Log"></bean>
        <bean id="afterlog" class="com.lzj.log.AfterLog"></bean>
    <!--    Method 2: user defined class-->
        <bean id="diy" class="com.lzj.diy.DiyPointCut"></bean>
        <aop:config>
    <!--        Custom section, ref Class to reference-->
            <aop:aspect ref="diy">
    <!--            breakthrough point-->
                <aop:pointcut id="pointcut" expression="execution(* com.lzj.service.UserServiceImpl.*(..))"/>
    <!--            notice-->
                <aop:before method="before" pointcut-ref="pointcut"/>
                <aop:after method="after" pointcut-ref="pointcut"/>
            </aop:aspect>
        </aop:config>
    </beans>
    
  6. test

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //Dynamic proxy is the interface
            UserService userservice = (UserService) context.getBean("userservice");
            userservice.add();
        }
    }
    

Implementing AOP with annotations

Compared with using custom class AOP, the custom class and xml configuration file are modified

Code steps:

  1. Import dependency

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

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void select();
    }
    
  3. Implementation class

    public class UserServiceImpl implements UserService{
        @Override
        public void add() {
            System.out.println("Added a user");
        }
    
        @Override
        public void delete() {
            System.out.println("A user was deleted");
        }
    
        @Override
        public void update() {
            System.out.println("Updated a user");
        }
    
        @Override
        public void select() {
            System.out.println("Queried a user");
        }
    }
    
  4. Custom class

    //Implement AOP with annotation
        @Aspect
    public class AnnotationPointCut {
        @Before("execution(* com.lzj.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("=========Before method execution=========");
        }
        @After("execution(* com.lzj.service.UserServiceImpl.*(..))")
        public void after(){
    
            System.out.println("=========After method execution=========");
        }
        //In surround enhancement, we can give a parameter to represent the point where we want to get the processing entry point
        @Around("execution(* com.lzj.service.UserServiceImpl.*(..))")
        public void around(ProceedingJoinPoint jp) throws Throwable {
            System.out.println("Surround front");
            Signature signature = jp.getSignature();//Get signature
            System.out.println("signature"+signature);
            Object proceed = jp.proceed();//Execution method
            System.out.println("After surround");
    
        }
    }
    
    
  5. xml configuration

    You need to import xml constraints before

    <?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">
    
    <!--    register bean-->
        <bean id="userservice" class="com.lzj.service.UserServiceImpl"></bean>
        <bean id="log" class="com.lzj.log.Log"></bean>
        <bean id="afterlog" class="com.lzj.log.AfterLog"></bean>
    <!--    Method 3: implement with annotation AOP-->
        <bean id="annotation" class="com.lzj.diy.AnnotationPointCut"/>
    <!--    Enable annotation support-->
        <aop:aspectj-autoproxy/>
    </beans>
    
  6. test

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //Dynamic proxy is the interface
            UserService userservice = (UserService) context.getBean("userservice");
            userservice.add();
        }
    }
    

The difference between aspect and advice

When defining facets, you only need to define general bean s. When defining notifications referenced in < AOP: advisor >, the notifications must implement the Advice interface

< AOP: advisor > and < AOP: aspect > actually encapsulate the notification and aspect. The principle is basically the same, but they are used in different ways

  • < AOP: aspect >: define facets (facets include notifications and pointcuts)
  • < AOP: aspect > is mostly used for logging and caching
  • < AOP: advisor >: define the notifier (the notifier is the same as the aspect, including notification and pointcut)
  • < AOP: advisor > is mostly used for transaction management

Integrate Mybatis

Steps:

  1. Import related jar packages

    • junit

    • mybatis

    • mysql database

    • spring related

    • aop implantation

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.7</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.3.15</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.15</version>
            </dependency>
    <!--        use Spring of API realization Aop-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.7</version>
            </dependency>
    <!--        integration mybatis and spring-->
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.6</version>
            </dependency>
        </dependencies>
    
  2. Write configuration file

  3. test

Integration mode I

Adopt SqlSessionTemplate

  1. Write spring Dao XML configuration file

    Write data source configuration, sqlSessionFactory and sqlISessionTemplate

    <?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:util="http://www.springframework.org/schema/util"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
    
    <!--    DataSource:use Spring Data source replacement for Mybatis Configuration of c3p0    dbcp   druid
            We use it here Spring Provided JDBC:org.springframework.jdbc.datasource
    -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url"
                      value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    
    <!--    sqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
    <!--        binding Mybatis configuration file-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:com/lzj/dao/*.xml"/>
        </bean>
    
    <!--    SqlSessionTemplate: That's what we use sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--        Only constructor injection can be used sqlSessionFactor,Because it doesn't set method-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
        
    </beans>
    
  2. You need to add an implementation class [] to the interface

    Interface

    public interface UserMapper {
        public List<User> queryUser();
    }
    

    UserMapper.xml configuration file

    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--namespace=Bind a corresponding Dao/Mapper Interface-->
    <mapper namespace="com.lzj.dao.UserMapper">
        <!--    select query-->
        <!--    id Name of the corresponding interface method-->
        <select id="queryUser" resultType="user">
            select * from mybatis.user
        </select>
    </mapper>
    

    Implementation class

    public class UserMapperImpl implements UserMapper{
        //All our operations are executed using sqlSession. Now we use SqlSessionTemplate
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        @Override
        public List<User> queryUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.queryUser();
        }
    }
    
  3. Inject the implementation class written by yourself into Spring and write Spring Dao The XML configuration file is introduced into the applicationContext.xml of Spring XML configuration file

    <?xml version="1.0" encoding="UTF-8"?>
    <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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <import resource="spring-dao.xml"></import>
    
        <bean id="userMapper" class="com.lzj.dao.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    </beans>
    
  4. Test and use|

    @Test
    public void queryUserTest2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List<User> users = userMapper.queryUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
    

Integration mode II

Inherit SqlSessionDaoSupport class

You can delete spring Dao SqlSessionTemplate in XML configuration file

  1. Implementation interface class

    public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
        @Override
        public List<User> queryUser() {
            return getSqlSession().getMapper(UserMapper.class).queryUser();
        }
    }
    
  2. Registering interface classes in xml

    <bean id="userMapper2" class="com.lzj.dao.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    
  3. test

    @Test
    public void queryUserTest3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        List<User> users = userMapper.queryUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
    

Transaction management in spring

Transaction ACID principle:

  • Atomicity
  • uniformity
  • Isolation
    • Multiple businesses may operate the same resource to prevent data corruption
  • persistence
    • Once the transaction is committed, no matter what happens to the system, the result will not be affected and will be written to the memory persistently!

Declarative transaction

AOP

Add the following configuration in spring Dao

<!--    Configure declarative transactions-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
<!--    combination AOP Implement transaction placement-->
<!--    Configure transaction notifications-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    Configure transaction pointcuts-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.lzj.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

Programming transaction

You need to manage transactions in your code

Why transactions are needed

  • If transactions are not configured, there may be inconsistent data submission;
  • If we do not configure declarative transactions in SPRING, we need to manually configure transactions in the code!
  • Transaction is very important in the development of the project. It involves the consistency and integrity of data, which should not be careless!
    serMapper.class);
    List users = userMapper.queryUser();
    for (User user : users) {
    System.out.println(user);
    }
    }

Transaction management in spring

Transaction ACID principle:

  • Atomicity
  • uniformity
  • Isolation
    • Multiple businesses may operate the same resource to prevent data corruption
  • persistence
    • Once the transaction is committed, no matter what happens to the system, the result will not be affected and will be written to the memory persistently!

Declarative transaction

AOP

Add the following configuration in spring Dao

<!--    Configure declarative transactions-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
<!--    combination AOP Implement transaction placement-->
<!--    Configure transaction notifications-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    Configure transaction pointcuts-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.lzj.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

Programming transaction

You need to manage transactions in your code

Why transactions are needed

  • If transactions are not configured, there may be inconsistent data submission;
  • If we do not configure declarative transactions in SPRING, we need to manually configure transactions in the code!
  • Transaction is very important in the development of the project. It involves the consistency and integrity of data, which should not be careless!

Keywords: Java Spring

Added by ultrus on Fri, 18 Feb 2022 00:25:43 +0200