In a word:

Spring is a lightweight Inversion of Control (IoC) and Aspect Oriented (AOP) container (framework).

composition

  • Core container: The core container provides the basic functionality of the Spring framework. The main component of the core container is the BeanFactory, which is an implementation of the factory pattern.

    BeanFactory uses the Inversion of Control (IOC) pattern to separate the application’s configuration and dependency specifications from the actual application code.

  • Spring context: Simply understand the current environment in which Spring is running, but also understand the resources Spring can use.

  • Spring AOP: Aspect oriented programming capabilities that provide transaction management services.

    By using Spring AOP, you can integrate declarative transaction management into your application without relying on components.

  • Spring DAO: Spring DAO’s JDBC-oriented exceptions follow the common DAO exception hierarchy.

  • Spring ORM: Object Relational Mapping.

    Used to convert data between different type systems in object-oriented programming languages

  • Spring Web module: The Web context module builds on the application context module and provides context for web-based applications.

  • Spring MVC Framework: The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework becomes highly configurable through the policy interface, and MVC accommodates a number of view technologies, including JSP, Velocity, Tiles, iText, and POI.

Spring Boot and Spring Cloud

  • Spring Boot is a set of quick configuration scaffolding for Spring that allows you to quickly develop individual microservices based on Spring Boot.
  • Spring Cloud is implemented based on Spring Boot.
  • While Spring Boot focuses on a single microservice individual that can be quickly and easily integrated, Spring Cloud focuses on a global service governance framework.
  • Spring Boot uses the concept of constraint over configuration. Many integration solutions have been chosen for you, and if you can, you can’t configure them. A large part of the Implementation of Spring Cloud is based on Spring Boot. Spring Boot can be independently used for development projects without Spring Cloud, but Spring Cloud cannot be separated from Spring Boot, which belongs to the dependency relationship.
  • SpringBoot acts as a link between the preceding and the following in SpringClound.

IOC

Inversion of Control (IoC) is a design idea, and DI is a method to implement IoC.

  • Control: Who controls the creation of objects. In traditional applications, objects are created by the program itself. With Spring, objects are created by Spring
  • Reverse: The program itself does not create objects, but becomes passive receivers of objects.

Dependency Injection (DI) : This is done using the set method.

IOC is a programming idea, from active programming to passive reception

In short: Objects are created, managed, and assembled by Spring!

Before designing a piece of code:

// Write a UserDao interface first
public interface UserDao {
   public void getUser(a);
}

// Write the Dao implementation class
public class UserDaoImpl implements UserDao {
   @Override
   public void getUser(a) {
       System.out.println("Access to user data"); }}// Then write the interface of UserService
public interface UserService {
   public void getUser(a);
}

// Finally write the implementation class of the Service
public class UserServiceImpl implements UserService {
   private UserDao userDao = new UserDaoImpl();

   @Override
   public void getUser(a) { userDao.getUser(); }}Copy the code

When you implement the class +++++++

A lot of code needs to be changed, and the design is too coupled.

We can, where we need to use it, not implement it, but set aside an interface, use set, and we’ll go and modify it in the code.

public class UserServiceImpl implements UserService {
   private UserDao userDao;
// Use set
   public void setUserDao(UserDao userDao) {
       this.userDao = userDao;
  }

   @Override
   public void getUser(a) { userDao.getUser(); }}Copy the code

Everything used to be created by the program, but now it’s up to us to create objects ourselves.

The program doesn’t care how it’s created, how it’s implemented, it just provides an interface.

DI

  • Dependency Injection (DI).
  • Dependency: The creation of a Bean object depends on the container, and the Bean object depends on the resource.
  • Injection: Refers to the resource on which the Bean object depends, which is set and assembled by the container.

1. Constant injection

<bean id="student" class="com.zwt.pojo.Student">
     <property name="name" value="Xiao Ming"/>
</bean>
    
   
    
@Test
 public void test01(a){
     ApplicationContext context = new 			  ClassPathXmlApplicationContext("applicationContext.xml");
 
     Student student = (Student) context.getBean("student");
 
     System.out.println(student.getName());
 
 }
Copy the code

2. Bean injection

Note: the value here is a reference, ref.

 <bean id="addr" class="com.zwt.pojo.Address">
     <property name="address" value="Chongqing"/>
 </bean>
 
 <bean id="student" class="com.zwt.pojo.Student">
     <property name="name" value="Xiao Ming"/>
     <property name="address" ref="addr"/>
 </bean>
Copy the code

3. Properties injection

<property name="info">
     <props>
         <prop key="Student id">20190604</prop>
         <prop key="Gender"</p > <p style = "text-align: center"Name"</prop> </prop> </prop>Copy the code

…………………

P named and C named injection

1. P namespace injection: constraint files need to be added to header files

Import constraint: XMLNS :p="http://www.springframework.org/schema/p"<! --P(properties: properties) namespace, properties are still set to the set method --> <bean ID ="user" class="com.zwt.pojo.User" p:name="zwt" p:age="18"/>
Copy the code

2, C namespace injection: need to add constraint files to the header (write a parameter construct)

Import constraint: XMLNS :c="http://www.springframework.org/schema/c"<! --C(Constructor: Constructor) namespace, attribute still set the set method --> <bean ID ="user" class="com.kuang.pojo.User" c:name="Crazy god" c:age="18"/>
Copy the code

Bean

In Spring, the objects that make up the bulk of an application and are managed by the Spring IoC container are called beans.

Simply put, beans are objects that are initialized, assembled, and managed by the IoC container.

Several scopes:

Singleton

There will only be one shared bean instance in the Spring IoC container, and all requests for beans with ids that match the bean definition will return only the same instance of the bean.

When you create a container, you automatically create an object for the bean. It exists whether you use it or not. Every time you get the same object, you get the same object.

Note that the Singleton scope is the default scope in Spring.

 <bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
Copy the code

Prototype

Represents a bean definition corresponding to multiple object instances.

The Prototype-scoped bean causes a new bean instance to be created every time the bean is requested.

A Prototype is a type that is not instantiated when we create the container. Instead, we create an object when we get the bean. Each time we get the bean, we get a different object.

 <bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>    
 
 或者 
 
 <bean id="account" class="com.foo.DefaultAccount" singleton="false"/>

Copy the code

Request

Represents one instance of a bean definition per HTTP request.

That is, each HTTP request has its own bean instance, which is created based on a bean definition.

This scope is only valid in the context of the Web-based Spring ApplicationContext.

 <bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>

Copy the code

For each HTTP request, the Spring container creates a new loginAction Bean instance based on the loginAction Bean’s definition,

The loginAction Bean instance is available only within the current HTTP Request.

When processing the request is complete, the request scoped bean instance will be destroyed.

Session

Represents one instance of a bean definition in an HTTP Session.

This scope is only valid in the context of the Web-based Spring ApplicationContext.

 <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

Copy the code

For an HTTP Session, the Spring container creates a new Instance of the userPreferences Bean based on the userPreferences Bean definition,

The userPreferences bean is valid only for the current HTTP Session.

When an HTTP Session is finally discarded, beans in the scope of that HTTP Session are also discarded.

Automatically.

  • Autowiring is one way to satisfy bean dependencies using Spring
  • Spring looks for a bean’s dependencies in the application context.

There are three assembly mechanisms for beans in Spring, which are:

  1. Explicitly configured in XML;
  2. Explicitly configured in Java;
  3. Implicit bean discovery mechanism and auto-assembly.

Automated assembly of beans:

  1. Component scanning: Spring automatically discovers beans created in the application context.
  2. Autowiring: Spring automatically satisfies the dependencies between the beans, which we refer to as IoC/DI.

The combination of component scanning and autolower plays a huge role in minimizing the number of displayed configurations.

It is recommended to use annotations for auto-assembly

1. Introduce the Context header into the Spring configuration file

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd

Copy the code

2, enable attribute annotation support!

<context:annotation-config/>

Copy the code

@Autowired

  • @autowired is automatically transferred by type and does not support ID matching.
  • Need to import spring-AOP packages!

Testing:

public class User {
   @Autowired
   private Cat cat;
   
   private String str;

   public Cat getCat(a) {
       return cat;
  }
   
   public String getStr(a) {
       returnstr; }}Copy the code

2. Configure the contents of the file

<context:annotation-config/>

<bean id="dog" class="com.zwt.pojo.Dog"/>

Copy the code

@autowired (required=false) : false, objects can be null; True, object must store object, cannot be null.

// If null is allowed, set required = false. The default is true@Autowired(required = false)private Cat Cat;Copy the code

@Qualifier

  • @autowired is autoassembled by type, and @Qualifier is autoassembled by byName
  • Qualifier cannot be used alone.

1. Modify the content of the configuration file to ensure that the type exists. The name is not the default name of the class!

<bean id="dog1" class="com.zwt.pojo.Dog"/>
<bean id="dog2" class="com.zwt.pojo.Dog"/>
<bean id="cat1" class="com.zwt.pojo.Cat"/>
<bean id="cat2" class="com.zwt.pojo.Cat"/>

Copy the code

1) No Qualifier test is added

Add a Qualifier annotation to the property

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

Copy the code

Test, successful output!

@Resource

  • @resource if there is a specified name attribute, first use the attribute to find the assembly byName;
  • Secondly, the assembly is carried out in the default byName mode.
  • If all else fails, auto-assemble as byType.
  • Are unsuccessful, an exception is reported.

Entity class:

public class User {
   // If null is allowed, set required = false, which defaults to true
   @Resource(name = "cat2")
   private Cat cat;
   @Resource
   private Dog dog;
   private String str;
}
Copy the code

beans.xml

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>
Copy the code

Test: the result is OK

Configuration file 2: beans.xml, delete cat2

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
Copy the code

Only annotations remain on the entity class

@Resource
private Cat cat;
@Resource
private Dog dog;
Copy the code

Results: OK

Conclusion: The byName search failed; The byType search succeeds.

summary

@autowired and @Resource:

1. Both @AutoWired and @Resource can be used to assemble beans. You can write it on a field, you can write it on a setter method.

2. @AutoWired defaults to assembly by type (which is part of the Spring specification) and must require that the dependent object exists by default. To allow null values, you can set its required attribute to false.

For example, @autowired (Required =false) can be used in conjunction with the @Qualifier annotation if we want to use name assembly

3. @Resource (which belongs to J2EE return), by default, is assembled by name, which can be specified through the name attribute.

@autowired first byType, @Resource first byName.

Static and dynamic proxies

The underlying mechanism of AOP is dynamic proxy

Static agent

The so-called agent model, the program is derived from life

Just like in real life when you rent a house, you can’t see the landlord, but you still rent the landlord’s house through the agent.

Advantages:

  • Can make our real role more pure. No longer concerned with some public things.
  • The public business is completed by the agent, which realizes the division of business.
  • Common business becomes more centralized and convenient as it expands.

Disadvantages:

  • More classes, more proxy classes, the amount of work becomes larger. Development efficiency is reduced.
// Abstract role: renting a house
public interface Rent {
   public void rent(a);
}


// Real role: landlord, landlord to rent the house
public class Host implements Rent{
   public void rent(a) {
       System.out.println("House for rent"); }}// Agent role: mediator
public class Proxy implements Rent {

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

   / / rent
   public void rent(a){
       seeHouse();
       host.rent();
       fare();
  }
   / / the checking
   public void seeHouse(a){
       System.out.println("Show the tenants.");
  }
   // Collect an intermediary fee
   public void fare(a){
       System.out.println("Collect an intermediary fee"); }}// For customers, usually customers will go to the agent!
public class Client {
   public static void main(String[] args) {
       // The landlord wants to rent a house
       Host host = new Host();
       // The agent helps the landlord
       Proxy proxy = new Proxy(host);

       // You go to the intermediary!proxy.rent(); }}Copy the code

A dynamic proxy

  • Dynamic proxies fall into two categories: interface-based and class-based

    • Interface-based dynamic proxy —-JDK dynamic proxy
    • Class-based dynamic proxy — CGLIb
    • More often than not, JAVAssist is used to generate dynamic proxies

The JDK’s dynamic proxy requires knowledge of two classes:

Core: InvocationHandler and Proxy

Object invoke(Object proxy, method, Object[] args);

Proxy – The proxy instance that calls the method

Method – The method corresponds to an instance of the interface method on the invoking proxy instance.

The declaring class of the method object will be the interface declared by the method, which can be the superinterface of the proxy interface from which the proxy class inherits the method.

Args – contains an array of objects whose method calls pass proxy instance parameter values, or null if the interface method has no parameters.

The parameters of the primitive type are contained in an instance of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.boolean.

// Generate the proxy class
public Object getProxy(a){
   return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                                 rent.getClass().getInterfaces(),this);
}

Copy the code

Example:

// Abstract role: renting a house
public interface Rent {
   public void rent(a);
}

// Real role: landlord, landlord to rent the house
public class Host implements Rent{
   public void rent(a) {
       System.out.println("House for rent"); }}/ / ProxyInvocationHandler. Java agent role
public class ProxyInvocationHandler implements InvocationHandler {
   private Rent rent;

   public void setRent(Rent rent) {
       this.rent = rent;
  }

   // Generate the proxy class, focusing on the second argument, which gets the abstract role to proxy! What used to be one role can now proxy a class of roles
   public Object getProxy(a){
       return Proxy.newProxyInstance(this.getClass().getClassLoader(),
               rent.getClass().getInterfaces(),this);
  }

   Method: method object for the invocation handler of the proxy class.
   // Process the method call on the proxy instance and return the result
   @Override
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       seeHouse();
       // Core: essence is realized by reflection!
       Object result = method.invoke(rent, args);
       fare();
       return result;
  }

   / / the checking
   public void seeHouse(a){
       System.out.println("Show the tenants.");
  }
   // Collect an intermediary fee
   public void fare(a){
       System.out.println("Collect an intermediary fee"); }} / tenantpublic class Client {

   public static void main(String[] args) {
       // Real characters
       Host host = new Host();
       // Call handler for the proxy instance
       ProxyInvocationHandler pih = new ProxyInvocationHandler();
       pih.setRent(host); // Put real characters in it!
       Rent proxy = (Rent)pih.getProxy(); // Generate the corresponding proxy class dynamically!proxy.rent(); }}Copy the code

Core: a dynamic proxy, general proxy a certain kind of business, a dynamic proxy can proxy more than one class, the proxy is the interface!

Advantages:

  • Can make our real role more pure. No longer concerned with some public things.
  • The public business is completed by the agent, which realizes the division of business.
  • Common business becomes more centralized and convenient as it expands.
  • A dynamic proxy, generally a proxy for a certain type of business
  • A dynamic proxy can proxy multiple classes, the proxy is the interface!

AOP

Aspect Oriented Programming (AOP) refers to Aspect Oriented Programming.

A technique that implements unified maintenance of program functions by means of precompilation and dynamic proxy at run time.

AOP is a continuation of OOP, a hot topic in software development, an important content in Spring framework, and a derivative paradigm of functional programming.

Using AOP can isolate each part of the business logic, so that the coupling degree between each part of the business logic is reduced, the reusability of the program is improved, and the efficiency of development is improved.

role

Provides declarative transactions that allow users to customize aspects.

In SpringAOP, crosscutting logic is defined by Advice. Spring supports five types of Advice:

  1. Front enhancement (org. Springframework. Aop. BeforeAdvice) said in the target method to implement enhancements
  2. Rear enhancement (org. Springframework. Aop. AfterReturningAdvice) said the target method performs when implementing increased
  3. Surrounding the enhancement (org. Aopalliance. Intercept. MethodInterceptor) said in the target method perform before and after the implementation of the enhanced at the same time
  4. Exception thrown enhancement (org. Springframework. Aop. ThrowsAdvice) said in the target method throws an exception when implementing increased
  5. Introducing enhancement (org. Springframework. Aop. Introductioninterceptor) said in the target class to add some new methods and properties

That is, Aop adds new functionality without changing existing code.

【 Key 】 With 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.94.</version>
</dependency>

Copy the code

The first approach (implemented through the Spring API)

// First write our business interface and implementation class
public interface UserService {

   public void add(a);

   public void delete(a);

}


public class UserServiceImpl implements UserService{

   @Override
   public void add(a) {
       System.out.println("Add users");
  }

   @Override
   public void delete(a) {
       System.out.println("Delete user"); }}// Then to write our enhancement class, we write two, one pre-enhancement and one post-enhancement

public class Log implements MethodBeforeAdvice {

   //method: specifies the method of the target object to be executed
   //objects: arguments to the method being called
   //Object: indicates the target Object
   @Override
   public void before(Method method, Object[] objects, Object o) throws Throwable {
       System.out.println( o.getClass().getName() + "The" + method.getName() + "The method is executed."); }}public class AfterLog implements AfterReturningAdvice {
   / / the returnValue return values
   //method Specifies the method to be called
   //args Specifies the parameters of the object to which the method is called
   //target Specifies the target object to be called
   @Override
   public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
       System.out.println("Executed." + target.getClass().getName()
       +"The"+method.getName()+"Method."
       +Return value:+returnValue); }}// Finally go to the spring file registration, and implement the AOP access implementation, pay attention to the import constraints<? 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.zwt.service.UserServiceImpl"/>
   <bean id="log" class="com.zwt.log.Log"/>
   <bean id="afterLog" class="com.zwt.log.AfterLog"/ > <! --aop --> <aop:config> <! -- pointcut expression: expression matches the method to execute --> < AOP :pointcut id="pointcut" expression="execution(* com.zwt.service.UserServiceImpl.*(..) )"/ > <! -- Perform surround; Pointcut -ref --> < AOP: Advisor advice-ref="log" pointcut-ref="pointcut"/>
       <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans> testpublic class MyTest {
   @Test
   public void test(a){
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService"); userService.search(); }}Copy the code

Spring’S Aop is about combining common business (logging, security, etc.) with domain business,

When the domain business is executed, common business will be added. Reuse of common business will be achieved

Domain business is more pure, focus on domain business, its essence is still dynamic proxy.

Second approach (Custom classes to implement Aop)

// Step 1: Write a class of our own

public class DiyPointcut {

   public void before(a){
       System.out.println("--------- method before ---------");
  }
   public void after(a){
       System.out.println("--------- method executes ---------"); }}// Go to Spring to configure<! --> <! -- Register bean--> <bean id="diy" class="com.zwt.config.DiyPointcut"/ > <! --aop --> <aop:config> <! > < AOP :aspect ref="diy">
       <aop:pointcut id="diyPonitcut" expression="execution(* com.zwt.service.UserServiceImpl.*(..) )"/>
       <aop:before pointcut-ref="diyPonitcut" method="before"/>
       <aop:after pointcut-ref="diyPonitcut" method="after"/>
   </aop:aspect>
</aop:config>

  
    

public class MyTest {
   @Test
   public void test(a){
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService"); userService.add(); }}Copy the code

Third way (using annotations)

// Step 1: Write an annotated implementation of the enhanced class

@Aspect
public class AnnotationPointcut {
   @Before("execution(* com.kuang.service.UserServiceImpl.*(..) )"
   public void before(a){
       System.out.println("--------- method before ---------");
  }

   @After("execution(* com.kuang.service.UserServiceImpl.*(..) )"
   public void after(a){
       System.out.println("--------- method executes ---------");
  }

   @Around("execution(* com.kuang.service.UserServiceImpl.*(..) )"
   public void around(ProceedingJoinPoint jp) throws Throwable {
       System.out.println("Around the front.");
       System.out.println("Signature."+jp.getSignature());
       // Proceed with the target method
       Object proceed = jp.proceed();
       System.out.println("After surround"); System.out.println(proceed); }}// Step 2: In the Spring configuration file, register the bean and add a configuration that supports annotations<! --> <bean id="annotationPointcut" class="com.zwt.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>
    
    

Copy the code

< AOP :aspectj-autoproxy /> declaration via the AOP namespace

Automatically create proxies for beans in the Spring container that configure the @AspectJ aspect, weaving the aspect.

And, of course, the spring in internal using AnnotationAwareAspectJAutoProxyCreator to create work of automatic agent,

But the implementation details have been hidden by < AOP :aspectj-autoproxy />

<aop:aspectj-autoproxy /> has a proxy-target-class attribute, which defaults to false, indicating that JDK dynamic proxy is used for weaving enhancements,

< AOP: aspectj-Autoproxy poxy-target-class=”true”/> indicates that CGLib dynamic proxy technology is used for weaving enhancement.

However, even if proxy-target-class is set to false, Spring automatically uses the CGLib dynamic proxy if the target class does not declare an interface.

Reference links:

www.bilibili.com/video/BV1WE…