What is Spring and understanding of Spring (IOC,AOP)

Posted by rdog157h on Sat, 22 Jan 2022 06:09:10 +0100

Spring framework is the most widely used framework in Java. Its success comes from the concept rather than the technology itself. Its concepts include ^ IoC (Inversion of Control) and ^ AOP(Aspect Oriented Programming).

1|0 what is Spring:

1. Spring is a lightweight open source framework for DI / IoC and AOP containers, derived from some concepts and prototypes described by Rod Johnson in his book Expert one on one J2EE design and development.
2. Spring advocates "least intrusion" to manage the code in the application, which means that we can install or uninstall spring at any time

  • Scope of application: any Java application
  • Spring's fundamental mission: simplifying Java development

1. Common terms in spring:

1. Frame:

It is a semi-finished product that can complete certain functions.

What the framework can help us complete are: the overall framework of the project, some basic functions, how to create classes and objects, how to cooperate, etc. when we develop a project, the framework helps us complete some functions. If we complete another part ourselves, the project will be completed.

2. Non intrusive design:

From the perspective of the framework, it can be understood that there is no need to inherit any classes provided by the framework. In this way, when we change the framework, the previously written code can almost continue to be used.

3. Lightweight and heavyweight:

Lightweight is relative to heavyweight. Lightweight is generally non-invasive, relies on very few things, occupies very few resources, is simple to deploy, etc. in fact, it is relatively easy to use, while heavyweight is just the opposite.

4,JavaBean:
Java classes that conform to the JavaBean specification
5,POJO:

Plain Old Java Objects, simple old-fashioned Java objects, can contain business logic or persistence logic, but do not play any special role and do not inherit or implement classes or interfaces of any other Java framework.

6. Container:

In daily life, a container is an appliance for holding things. From the perspective of program design, it is the object for holding objects. Because there are operations such as putting in and taking out, the container also manages the life cycle of objects.

1|2Spring's advantages:

  • Low intrusion / low coupling (reduce the coupling degree between components and realize the decoupling between software layers)
  • Declarative transaction management (based on aspects and conventions)
  • Facilitate integration with other frameworks (e.g. MyBatis, Hibernate)
  • Reduce the difficulty of Java development
  • The Spring framework includes the solution of each of the three layers of J2EE (one-stop)

What can spring do for us

① Spring can help us create and assemble dependencies between objects according to configuration files.
  ②. Spring aspect oriented programming can help us realize logging, performance statistics and security control without coupling.
  ③. Spring can easily help us manage database transactions.
  ④. Spring also provides seamless integration with third-party data access frameworks (such as Hibernate and JPA), and it also provides a set of JDBC access templates to facilitate database access.
  ⑤. Spring also provides seamless integration with third-party Web (such as struts 1 / 2 and JSF) frameworks, and it also provides a set of Spring MVC framework to facilitate the construction of web layer.
  ⑥. Spring can easily integrate with Java EE (such as Java Mail and task scheduling) and more technologies (such as caching framework).

1. Frame structure of 4spring:

  • The Data Access/Integration layer includes JDBC, ORM, OXM, JMS and Transaction modules.
  • The Web layer includes Web, Web servlet, WebSocket and Web pocket modules.
  • AOP module provides an implementation of aspect oriented programming in accordance with AOP alliance standard.
  • Core container: contains Beans, core, Context and spiel modules.
  • The Test module supports testing Spring components using JUnit and TestNG.

2|0Spring IOC and DI:

2|1IOC: reverse of control

  • Read as "reverse control", it is better understood that it is not a technology, but a design idea, that is, to hand over the control of manually creating objects in the program to the Spring framework.
  • Positive control: if you want to use an object, you need to be responsible for the creation of the object
  • Anti control: if you want to use an object, you only need to obtain the object to be used from the Spring container, and you don't care about the object creation process, that is, you reverse the control of creating the object to the Spring framework
  • Hollywood Law: Don't call me, I'll call you

An example:

In real life, when people want to use something, their first reaction is to find it. For example, they want to drink fresh orange juice. In the days when there is no beverage store, the most intuitive way is to buy a juice machine, buy oranges, and then prepare boiled water. It is worth noting that these are all your own "active" creation process, that is, a glass of orange juice needs to be created by yourself.

However, today, due to the prevalence of beverage stores, when we want to drink orange juice, the first idea is to find the contact information of the beverage store, describe your needs, address and contact information through telephone and other channels, place an order and wait, and someone will deliver orange juice in a moment.

Please note that you do not "take the initiative" to create orange juice. Orange juice is created by the beverage store, not you. However, it fully meets your requirements and is even better than what you created.

2|2 write the first Spring program:

1. Create an empty Java project

2. Create a new directory named lib and add necessary jar packages

3. Create a new Source class:

package pojo;
 
public class Source {  
    private String fruit;   // type
    private String sugar;   // Sugar description
    private String size;    // Size cup    
    /* setter and getter */
}

4. Create an ApplicationContext xml file to assemble bean s through xml 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 name="source" class="pojo.Source">
        <property name="fruit" value="orange"/>
        <property name="sugar" value="Polysaccharide"/>
        <property name="size" value="venti "/>
    </bean>
</beans>

5. Create a new TestSpring class:

package test;
 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Source;
 
public class TestSpring {
 
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[]{"applicationContext.xml"}
        );
 
        Source source = (Source) context.getBean("source");
        System.out.println(source.getFruit());
        System.out.println(source.getSugar());
        System.out.println(source.getSize());
    }
}

2|3 summary:

1. Traditional method: actively create an object through the new keyword
2. IOC mode: the life cycle of an object is managed by Spring, and an object is obtained directly from Spring. IOC is the abbreviation of inversion of control, just as the control is handed over to Spring from its own hands.

DI: Dependency Injection

It refers to setting the object dependent properties (simple value, collection, object) to the object through configuration during the process of creating the object by Spring

---------------------------Continue with the example above----------------------------------

Create a new JuiceMaker class under pojo:

package pojo;
 
public class JuiceMaker {
 
    // A Source object is uniquely associated
    private Source source = null;
 
    /* setter and getter */
 
    public String makeJuice(){
        String juice = "xxx The user ordered a drink" + source.getFruit() + source.getSugar() + source.getSize();
        return juice;
    }
}

Configure the juiceMaker object in the xml 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 name="source" class="pojo.Source">
        <property name="fruit" value="orange"/>
        <property name="sugar" value="Polysaccharide"/>
        <property name="size" value="venti "/>
    </bean>
    <bean name="juickMaker" class="pojo.JuiceMaker">
        <property name="source" ref="source" />
    </bean>
</beans>

Add the following code in TestSpring:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.JuiceMaker;
import pojo.Source;
public class TestSpring {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[]{"applicationContext.xml"}
        );
 
        Source source = (Source) context.getBean("source");
        System.out.println(source.getFruit());
        System.out.println(source.getSugar());
        System.out.println(source.getSize());
 
        JuiceMaker juiceMaker = (JuiceMaker) context.getBean("juickMaker");
        System.out.println(juiceMaker.makeJuice());
    }
}

Run the code to test.

IoC and DI are actually descriptions of the same concept from different angles. DI clearly describes "the injected object depends on the IoC container configuration dependent object" relative to IoC

2 | 4 how is IOC realized

Finally, let's briefly talk about how IoC is implemented. Imagine if we implement this dependency injection function ourselves, how do we do it? Nothing more than:

1. Read the annotation or configuration file to see which Source JuiceMaker depends on and get the class name

2. Use the reflection API to instantiate the corresponding object instance based on the class name

3. Pass the object instance to JuiceMaker through constructor or setter

We find that it's not difficult to implement it by ourselves. Spring actually does that. In this way, IoC is actually an upgraded version of the factory model! Of course, there is still a lot of detailed work to do to build a mature IoC framework. Spring not only provides a Java IoC framework that has become the industry standard, but also provides more powerful functions, so don't build wheels! If you want to know more about the implementation details of IoC, you might as well deepen your understanding by learning the source code of spring!

3. Introduction to spring AOP:

If IoC is the core of Spring, aspect oriented programming is one of the most important functions of Spring. Aspect programming is widely used in database transactions.

AOP is aspect oriented programming
Firstly, in the idea of aspect oriented programming, the functions are divided into core business functions and peripheral functions.

  • The so-called core business, such as logging in, adding data and deleting data, is called core business
  • The so-called peripheral functions, such as performance statistics, logging, transaction management, and so on

Peripheral functions are defined as aspects in Spring's aspect oriented programming AOP idea. In the aspect oriented programming AOP idea, the core business functions and aspect functions are developed independently, and then the aspect functions and core business functions are "woven" together, which is called AOP.

3. Purpose of 1aop:

AOP can encapsulate the logic or responsibilities (such as transaction processing, log management, permission control, etc.) that have nothing to do with the business but are jointly invoked by the business modules, so as to reduce the repeated code of the system, reduce the coupling degree between modules, and facilitate the scalability and maintainability in the future.

3. Concepts in AOP:

Pointcut: on which classes and methods to cut (where)
Advice: what is actually done (when: before / after method / before and after method) during method execution (what: enhanced function)
Aspect: aspect = entry point + notification. The popular point is: when, where and what enhancement to do!
Weaving: the process of adding facets to objects and creating proxy objects. (completed by Spring)

3. AOP programming:

1. Create ProductService class:

package service;
 
public class ProductService {
    public void doSomeService(){
        System.out.println("doSomeService");
    }
}


2. Equip bean s in xml:

<bean name="productService" class="service.ProductService" />

3. Write test code in TestSpring:

public void test() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml") ;
    ProductService s = (ProductService) context.getBean("producrService");
    s.doSomeService();   
}

4. Prepare the LoggerAspect class:

package aspect;
 
import org.aspectj.lang.ProceedingJoinPoint;
 
public class LoggerAspect {
    
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("start log:" + joinPoint.getSignature().getName());
        Object object = joinPoint.proceed();
        System.out.println("end log:" + joinPoint.getSignature().getName());
        return object;
    }
}

5. Declare the business object and log aspect in the xml file:

Spring framework is the most widely used framework in Java. Its success comes from the concept rather than the technology itself. Its concepts include ^ IoC (Inversion of Control) and ^ AOP(Aspect Oriented Programming).

1|0 what is Spring:

1. Spring is a lightweight open source framework for DI / IoC and AOP containers, derived from some concepts and prototypes described by Rod Johnson in his book Expert one on one J2EE design and development.
2. Spring advocates "least intrusion" to manage the code in the application, which means that we can install or uninstall spring at any time

  • Scope of application: any Java application
  • Spring's fundamental mission: simplifying Java development

1. Common terms in spring:

1. Frame:

It is a semi-finished product that can complete certain functions.

What the framework can help us complete are: the overall framework of the project, some basic functions, how to create classes and objects, how to cooperate, etc. when we develop a project, the framework helps us complete some functions. If we complete another part ourselves, the project will be completed.

2. Non intrusive design:

From the perspective of the framework, it can be understood that there is no need to inherit any classes provided by the framework. In this way, when we change the framework, the previously written code can almost continue to be used.

3. Lightweight and heavyweight:

Lightweight is relative to heavyweight. Lightweight is generally non-invasive, relies on very few things, occupies very few resources, is simple to deploy, etc. in fact, it is relatively easy to use, while heavyweight is just the opposite.

4,JavaBean:
Java classes that conform to the JavaBean specification
5,POJO:

Plain Old Java Objects, simple old-fashioned Java objects, can contain business logic or persistence logic, but do not play any special role and do not inherit or implement classes or interfaces of any other Java framework.

6. Container:

In daily life, a container is an appliance for holding things. From the perspective of program design, it is the object for holding objects. Because there are operations such as putting in and taking out, the container also manages the life cycle of objects.

1|2Spring's advantages:

  • Low intrusion / low coupling (reduce the coupling degree between components and realize the decoupling between software layers)
  • Declarative transaction management (based on aspects and conventions)
  • Facilitate integration with other frameworks (e.g. MyBatis, Hibernate)
  • Reduce the difficulty of Java development
  • The Spring framework includes the solution of each of the three layers of J2EE (one-stop)

What can spring do for us

① Spring can help us create and assemble dependencies between objects according to configuration files.
  ②. Spring aspect oriented programming can help us realize logging, performance statistics and security control without coupling.
  ③. Spring can easily help us manage database transactions.
  ④. Spring also provides seamless integration with third-party data access frameworks (such as Hibernate and JPA), and it also provides a set of JDBC access templates to facilitate database access.
  ⑤. Spring also provides seamless integration with third-party Web (such as struts 1 / 2 and JSF) frameworks, and it also provides a set of Spring MVC framework to facilitate the construction of web layer.
  ⑥. Spring can easily integrate with Java EE (such as Java Mail and task scheduling) and more technologies (such as caching framework).

1. Frame structure of 4spring:

  • The Data Access/Integration layer includes JDBC, ORM, OXM, JMS and Transaction modules.
  • The Web layer includes Web, Web servlet, WebSocket and Web pocket modules.
  • AOP module provides an implementation of aspect oriented programming in accordance with AOP alliance standard.
  • Core container: contains Beans, core, Context and spiel modules.
  • The Test module supports testing Spring components using JUnit and TestNG.

2|0Spring IOC and DI:

2|1IOC: reverse of control

  • Read as "reverse control", it is better understood that it is not a technology, but a design idea, that is, to hand over the control of manually creating objects in the program to the Spring framework.
  • Positive control: if you want to use an object, you need to be responsible for the creation of the object
  • Anti control: if you want to use an object, you only need to obtain the object to be used from the Spring container, and you don't care about the object creation process, that is, you reverse the control of creating the object to the Spring framework
  • Hollywood Law: Don't call me, I'll call you

An example:

In real life, when people want to use something, their first reaction is to find it. For example, they want to drink fresh orange juice. In the days when there is no beverage store, the most intuitive way is to buy a juice machine, buy oranges, and then prepare boiled water. It is worth noting that these are all your own "active" creation process, that is, a glass of orange juice needs to be created by yourself.

However, today, due to the prevalence of beverage stores, when we want to drink orange juice, the first idea is to find the contact information of the beverage store, describe your needs, address and contact information through telephone and other channels, place an order and wait, and someone will deliver orange juice in a moment.

Please note that you do not "take the initiative" to create orange juice. Orange juice is created by the beverage store, not you. However, it fully meets your requirements and is even better than what you created.

2|2 write the first Spring program:

1. Create an empty Java project

2. Create a new directory named lib and add necessary jar packages

3. Create a new Source class:

package pojo;
 
public class Source {  
    private String fruit;   // type
    private String sugar;   // Sugar description
    private String size;    // Size cup    
    /* setter and getter */
}
 

4. Create an ApplicationContext xml file to assemble bean s through xml 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 name="source" class="pojo.Source">
        <property name="fruit" value="orange"/>
        <property name="sugar" value="Polysaccharide"/>
        <property name="size" value="venti "/>
    </bean>
</beans>
 

5. Create a new TestSpring class:

package test;
 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Source;
 
public class TestSpring {
 
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[]{"applicationContext.xml"}
        );
 
        Source source = (Source) context.getBean("source");
        System.out.println(source.getFruit());
        System.out.println(source.getSugar());
        System.out.println(source.getSize());
    }
}

2|3 summary:

1. Traditional method: actively create an object through the new keyword
2. IOC mode: the life cycle of an object is managed by Spring, and an object is obtained directly from Spring. IOC is the abbreviation of inversion of control, just as the control is handed over to Spring from its own hands.

DI: Dependency Injection

It refers to setting the object dependent properties (simple value, collection, object) to the object through configuration during the process of creating the object by Spring

---------------------------Continue with the example above----------------------------------

Create a new JuiceMaker class under pojo:

package pojo;
 
public class JuiceMaker {
 
    // A Source object is uniquely associated
    private Source source = null;
 
    /* setter and getter */
 
    public String makeJuice(){
        String juice = "xxx The user ordered a drink" + source.getFruit() + source.getSugar() + source.getSize();
        return juice;
    }
}

Configure the juiceMaker object in the xml 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 name="source" class="pojo.Source">
        <property name="fruit" value="orange"/>
        <property name="sugar" value="Polysaccharide"/>
        <property name="size" value="venti "/>
    </bean>
    <bean name="juickMaker" class="pojo.JuiceMaker">
        <property name="source" ref="source" />
    </bean>
</beans>

Add the following code in TestSpring:

 

import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.JuiceMaker; import pojo.Source; public class TestSpring { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext( new String[]{"applicationContext.xml"} ); Source source = (Source) context.getBean("source"); System.out.println(source.getFruit()); System.out.println(source.getSugar()); System.out.println(source.getSize()); JuiceMaker juiceMaker = (JuiceMaker) context.getBean("juickMaker"); System.out.println(juiceMaker.makeJuice()); } }

Run the code to test.

IoC and DI are actually descriptions of the same concept from different angles. DI clearly describes "the injected object depends on the IoC container configuration dependent object" relative to IoC

2 | 4 how is IOC realized

Finally, let's briefly talk about how IoC is implemented. Imagine if we implement this dependency injection function ourselves, how do we do it? Nothing more than:

1. Read the annotation or configuration file to see which Source JuiceMaker depends on and get the class name

2. Use the reflection API to instantiate the corresponding object instance based on the class name

3. Pass the object instance to JuiceMaker through constructor or setter

We find that it's not difficult to implement it by ourselves. Spring actually does that. In this way, IoC is actually an upgraded version of the factory model! Of course, there is still a lot of detailed work to do to build a mature IoC framework. Spring not only provides a Java IoC framework that has become the industry standard, but also provides more powerful functions, so don't build wheels! If you want to know more about the implementation details of IoC, you might as well deepen your understanding by learning the source code of spring!

3. Introduction to spring AOP:

If IoC is the core of Spring, aspect oriented programming is one of the most important functions of Spring. Aspect programming is widely used in database transactions.

AOP is aspect oriented programming
Firstly, in the idea of aspect oriented programming, the functions are divided into core business functions and peripheral functions.

  • The so-called core business, such as logging in, adding data and deleting data, is called core business
  • The so-called peripheral functions, such as performance statistics, logging, transaction management, and so on

Peripheral functions are defined as aspects in Spring's aspect oriented programming AOP idea. In the aspect oriented programming AOP idea, the core business functions and aspect functions are developed independently, and then the aspect functions and core business functions are "woven" together, which is called AOP.

3. Purpose of 1aop:

AOP can encapsulate the logic or responsibilities (such as transaction processing, log management, permission control, etc.) that have nothing to do with the business but are jointly invoked by the business modules, so as to reduce the repeated code of the system, reduce the coupling degree between modules, and facilitate the scalability and maintainability in the future.

3. Concepts in AOP:

Pointcut: on which classes and methods to cut (where)
Advice: what is actually done (when: before / after method / before and after method) during method execution (what: enhanced function)
Aspect: aspect = entry point + notification. The popular point is: when, where and what enhancement to do!
Weaving: the process of adding facets to objects and creating proxy objects. (completed by Spring)

3. AOP programming:

1. Create ProductService class:

package service;
 
public class ProductService {
    public void doSomeService(){
        System.out.println("doSomeService");
    }
}

2. Equip bean s in xml:

<bean name="productService" class="service.ProductService" />

3. Write test code in TestSpring:

public void test() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml") ;
    ProductService s = (ProductService) context.getBean("producrService");
    s.doSomeService();   
}

4. Prepare the LoggerAspect class:

package aspect;
 
import org.aspectj.lang.ProceedingJoinPoint;
 
public class LoggerAspect {
    
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("start log:" + joinPoint.getSignature().getName());
        Object object = joinPoint.proceed();
        System.out.println("end log:" + joinPoint.getSignature().getName());
        return object;
    }
}

5. Declare the business object and log aspect in the xml 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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <bean name="productService" class="service.ProductService" />
    <bean id="loggerAspect" class="aspect.LoggerAspect"/>
 
    <!-- to configure AOP -->
    <aop:config>
        <!-- where: Where (package).class.Method) add -->
        <aop:pointcut id="loggerCutpoint"
                      expression="execution(* service.ProductService.*(..)) "/>
 
        <!-- what:Do what to enhance -->
        <aop:aspect id="logAspect" ref="loggerAspect">
            <!-- when:At what time (before method)/after/(front and rear) -->
            <aop:around pointcut-ref="loggerCutpoint" method="log"/>
        </aop:aspect>
    </aop:config>
</beans>

6. Run the test code again. The code does not change, but the log information will be output before and after the business method is run.

Topics: Java JavaEE Spring