It’s Saturday, and it’s another day of fishing. I’m still a little out of shape today, and my brain is in a daze. I went out to drink coke last night and my brain is not normal till now. 450ml whisky +1L coke is just fine, maybe I can’t drink well), just want to organize my folder, found a spring-based mind map sorted out long ago, as follows:

Today, on the basis of this mind map, explain the basic content of Spring. Ok, let’s look at the detailed analysis of the text and code

If you need this mind map, you can follow the public account: Java Architect Union, and reply to Java in the background

What is the Spring

Spring is a lightweight inversion of Control (IOC) and AOP oriented container framework.

  • Lightweight: Spring is lightweight in terms of both size and overhead. The full Spring framework can be distributed in a jar file of just over 1MB in size; And the processing overhead required by Spring is trivial.
  • Non-invasive: There is generally no need to reference classes in the SpringJAR package in an application
  • Inversion of control: Spring’s core mechanism promotes loose coupling through inversion of control technology. Simply put, you give the object creation authority to the container and let the container manage the object.
  • Faceted: Allows the development of cohesion by separating the application’s business logic from system-level services. AOP is proxy-based, which in a more mundane way separates core business from system services (logging, permission management, and so on).

Spring’s core configuration and classes

  1. Applicationcontext.xml: core configuration file. Purpose: To configure all classes, which can be called SpringBeans
  2. BeanFactory: The container’s factory class (interface). Purpose: Used to create or get Spring beans, which are spring-managed objects.
  3. ApplicationContext: Application context (interface) It is a subclass of BeanFactory used to create or get SpringBeans. More powerful than BeanFactory.BeanFactoryandApplicationContextThe difference between:BeanFactoryLazy loading requires an object to loadApplicationContext: Non-lazy loading Loads all objects at once

Spring IOC

Inversion of control: Gives the creation and destruction of objects to the container framework, which manages the life cycle of objects. Ioc is not a new technology, just an idea or concept, to achieve loose coupling.

IOC includes dependency injection (DI, core) and dependency lookup.

DI: Dependency injection, which simply means that when Spring instantiates objects, the container sets their properties.

Spring’s injection method

Property injection (set method injection)

You have to have a setter method

The following code for the Spring configuration file is ignored by Java Beans.

<bean id="person" class="com.xx.Person">
	<property name = "name" value = "xzy"/>
	<property name = "coll">
		<list>
			<value>list</value>
			<value>list2</value>
		</list>
	</property>
	<property name = "map">
		<map>
			<entry key = "age" value = "21" />
    	</map>
    </property>
    <property name = "arr">
    	<array>
    		<value>java</value>
    		<value>C++</value>
    	</array>
    </property>
</bean>
Copy the code

Injection through the constructor

Need constructor, javaBean code:

public class User { private String name; private Integer age; public User(String name,Integer age){ this.name = name; this.age = age; }}Copy the code

Configuration file code:

<! <constructor-arg value = "Jay" ></constructor-arg> </constructor-arg> <constructor-arg value = "21" /> </bean> <! <constructor-arg value="44" index="1"/> <constructor-arg value="Jack"  index="0"/></bean> <! <constructor-arg value="44" name="age" /> <constructor-arg value="xxx" name = "name" /> </bean>Copy the code

Inject other classes

<! <bean id =" user" class =" com.xx. user" >< constructor-arg value="Jack"></constructor-arg> <constructor-arg value="44"></constructor-arg> <! Reference id--> <property name = "car" ref = "car"></property> </bean> <bean id = "car" class = "com.xx.car "> <property name = "type" value = "BWM"></property> </bean> <! -- Internal statement, stating in this way, <property name = "car"> <bean class = "cn.xx. car"> <property name = "type" value = "red flag "/> </bean> </property>Copy the code

Attributes in bean elements

  • Id: The unique identifier of the Bean
  • Name: Manage and configure beans by name. Multiple names can be separated by commas.
  • Class: Specifies the Bean’s concrete implementation class, which must be the fully qualified name of the utility class
  • Scope: Sets the scope of the Bean instance. Its properties are Singleton, Prototype, Request, Session, and Global Session. The default value is Singleton.
  • Constructor -arg:, which can be passed to instantiate the element’s index attribute specifying the ordinal number (starting from 0) of the constructor parameter.
  • Property:, which is assigned by calling setter methods in the Bean instance.
  • A child of elements such as ref:property, constructor-arg, where the bean attribute is used to specify a reference to a bean instance in the bean factory;
  • Value :property, constructor-arg, and other elements that directly specify a constant value;
  • List: Dependency injection used to encapsulate list or array types.
  • Set: Dependency injection used to encapsulate set or array types.
  • Map: Dependency injection used to encapsulate map or array types.
  • Entry: The children of the map element are used to set a key-value pair.

Instantiation of a Bean

Constructor instantiation

The Spring container instantiates the Bean through its corresponding default constructor.

Static factory instantiation

Create an instance of a Bean by creating a static factory

public class BeanFactory {
    public static Bean createBean(){
        return new Bean();
    }
}
<!--factory-method-->
<bean id = "bean" class = "com.xx.BeanFactory" factory-method = "createBean"></bean>
Copy the code

Instance factory mode instantiation

Instead of using static methods to create Bean instances, you create Bean instances directly.

Public BeanFactory {public BeanFactory(){system.err. Println ("BeanFactory factory instantiation ")} public static Bean createBean(){ return new Bean(); }} <! <bean id = "com.xx.beanFactory" class = "com.xx.beanFactory" /><! The --factory-bean property points to the configured instance factory; The factory-method attribute determines which method of the factory to use --> <bean id ="bean "factory-bean="beanFactory" factory-method="createBean"/>Copy the code

The scope of the Bean

Singleton: Singleton pattern

There is only one shared Bean instance in the Spring IOC container, always pointing to the same object no matter how many beans reference it.

<bean id ="dog" class =" com.bean. dog" scope="singleton"> public void test(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Dog dog1 = (Dog) ctx.getBean("dog"); System.err.println(dog1); Dog dog2 = (Dog) ctx.getBean("dog"); System.err.println(dog2); } // The output results are consistent, indicating the singleton mode.Copy the code

Prototype: Prototype

Each time a Prototype-defined bean is fetched from the Spring container, the container creates a new bean instance, each with its own properties and state.

request

In an Http request, the container returns the same instance of the Bean. New beans are generated for different Http requests and are valid only within the current HttpRequest. For each Http request, the Spring container creates a new instance of the bean based on its definition, and this instance is valid only for the current Http request. Other requests cannot see the state change in the current request. When the current Http request ends, the bean instance is destroyed.

session

In an Http Session, the container returns the same instance of the Bean. New instances are created for different Session requests, and the bean instance is valid only for the current Session. As with Http requests, a new instance is created for each session request, but no attributes are shared between different instances, and the instance is valid only for its own session request. When the request ends, the instance is destroyed.

How beans are assembled

Xml-based assembly

There are two types of assembly: setter injection and constructor injection.

Set two requirements for injection:

  • The Bean class must provide a default lunch constructor
  • The Bean class must provide the corresponding setter methods for the properties to be injected

Annotation based

Common notes:

  • @Component is a common form for all spring-managed components.
  • The @repository persistence layer is used, and the DAO layer is used.
  • @service Business class, which represents the business layer component used by the Service layer.
  • @Controller Indicates a Web layer component
  • Autowired assemble by type
  • @resource to assemble by name

Automatically.

Attribute Value Description Syntax Default Default value Determined by the value of the default-Autowire attribute default-Autowire = “default” byName Automatic assembly based on the attribute name byType Automatic assembly based on the data type of the attribute Constructor Automatic assembly based on the data type of the constructor parameter No Does not apply Automatic assembly, which must be defined by the REF element

Spring AOP

Realize the separation between core business and system service code through a special technical means to realize the core business runtime can realize the function of system service; The essence of AOP is that proxies intercept and enhance methods.

The basic concepts of AOP

Horizontal extraction is used to extract the same code that is scattered across methods and then apply the code to where it needs to be executed at the compiler or runtime.

Advice: Enhanced processing that AOP performs at the pointcut.

Type of notice:

  • MethodBeforeAdvice: Enhance a method before it executes
  • MethodAfterAdvice: methods are enhanced after they are executed
  • MethodInterceptor: Methods are enhanced before and after execution
  • AfterReturningAdvice: enhance after a successful return
  • Exception advice: Notification after an exception is thrown

Pointcuts: Join points with notifications about which methods of those classes are enhanced.

Types of pointcuts:

Based on regular expression JdkRegexpMethodPointcut

Based on the AspectJExpressionPointcut AspectJ expressions

Aspect: Usually a class that defines notifications and pointcuts

AOP = advice + pointcut

AOP case Java implementation

// com.bean.User public class User { public String login(String name){ return "name is "+ name ; } public String login(String name , int pwd){ return "name is "+name+", pwd is "+pwd ; Public MyAroundAdivice implements MethodInterceptor{@override Public Object invoke(MethodInvocation arg0) throws Throwable{ System.err.println(" New method :"+arg0.getMethod().getName()+","+ arg0.getarguments ()[0]); Object obj = arg0.proceed(); System.err. Println (" After execution...") ); return obj; }} @test public void Test (){// 1. Advice = new MyAroundAdivice(); / / 2, based on AspectJ statement tangent point object AspectJExpressionPointcut cut = new AspectJExpressionPointcut (); // set the expression /* return type com.bean.User login method parameter String */ //cut. SetExpression ("execution (String) com.bean.User.login(String))"); 0~n cut. SetExpression ("execution(* com.. * (..) ) "); //4, pointcut + advice =AOP Advisor Advisor = new DefaultPointcutAdvisor(cut, advice); ProxyFactory proxy = new ProxyFactory(new User()); //6, set aop proxy.addAdvisor(advisor); User User = (User) proxy.getProxy(); user.login("rose"); System.err.println("---------------"); user.login("jack",123); }Copy the code

AspectJ syntax

Everything in this directory, or in this class… Arbitrarily many. Execution (com.bean.user.login (String,int)) the execution (com.bean.user.login (String,int)) method must accept two arguments of type Strig,int, and return an unlimited value. And the method must be an Execution of the User class (* com.. (…). Return all types all classes in the COM package, all methods that do not contain subpackage classes take arbitrary multiple arguments 0~NExecution (* com… . (…). All methods in the com package, including all classes in the subpackage, are cut into execution(* com… (String)) | | execution (* com… . (*, int)) | | logic or

The AOP case is based on XML declarative AspectJ

<bean id = "user" class = "com.bean.User"> <! >< bean id="myBeforeAdvice" class=" com.demo3.myadvice "></bean> <aop:config> <! Configure pointcuts --> <! -- expressions (used to represent methods) --> <! -- Execution (< access modifier >? < return type >< method name >(< parameter >)< exception >), return value, method name, parameter can not be less --> <! -- * means: any value method name: full class name. In the method name parameter.. <aop:pointcut expression="execution(* com.. * (..) )" id="myPointcut" /> <! Aop :aspect ref="myBeforeAdvice"> <! Aop :before method="doBefore" pointcut-ref="myPointcut" /> <aop:before method="doBefore" pointcut-ref="myPointcut" /> <! Aop :after method="doAfter" pointcut-ref="myPointcut" /> <aop:after method="doAfter" pointcut-ref="myPointcut" /> <! Aop: post-returning method="doReturnAfter" pointcut-ref="myPointcut" /> <aop: post-returning method="doReturnAfter" pointcut-ref="myPointcut" /> <aop: post-returning method="doReturnAfter" pointcut-ref="myPointcut" /> Aop :around method="doAround" pointcut ="myPointcut" /> <aop:around method="doAround" pointcut ="myPointcut" /> /> </aop:aspect> </aop:aspect> </aop:config> </bean>Copy the code

Annotation-based declarative AspectJ (common)

Annotation @aspect annotation on a class that says this is an Aspect @pointcut annotation on a method that says this is a Pointcut, And declare aspectJ’s pointcut expression @after@afterretuning — correct execution returns a value @afterthrow — incorrect execution, and @around is notified After throwing an exception

Step 1: Create a facet class for the annotation

@pointcut @component public class MyAspect {// Define a Pointcut expression that names the Pointcut @pointcut ("execution(* com.. * (..) )") public void myPointCut(){} @before ("myPointCut()") public void doBefore(JoinPoint JoinPoint){ System.out.println(" prenotification, method start...") +": The target class is "+ joinPoint.gettarget ()+", the embedded enhancement method is: "+joinPoint.getSignature().getName()); } @after ("myPointCut()") public void doAfter() {system.out.println ("myPointCut()") public void doAfter() {system.out.println ("myPointCut()") ); } @afterreturning ("myPointCut()") public void doReturnAfter() {system.out.println (" returning ", "returning"... ); } /** * Surround the notification that the enhanced method used to call ProceedingJoinPoint must be the return type of Object and must accept a parameter, If the type is ProceedingJoinPoint *, throw Throwable */ @around ("myPointCut()") public Object doAround(ProceedingJoinPoint) JoinPoint) throws Throwable {system.out. println(" Surround notification: begin..." ); // Execute the enhanced method Object obj = joinPoint.proceed(); System.out.println(" Surround notification :end....." ); return obj; } @AfterThrowing(value="myPointCut()",throwing="e") public void doThrowing(Throwable e){ System.out.println(" exception notification......." +e.getMessage()); }}Copy the code

Step 2: XML configuration files

<bean id="user" class="com.bean.User"></bean> <context:component-scan base-package="com.xxx"></context:component-scan> <! < AOP :aspectj-autoproxy></ AOP: Aspectj-autoproxy >Copy the code

Step 3: Test the method

@Test
public void test1() {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("com/xxx/applicationContext.xml");
	User user = ctx.getBean("user",User.class);
	user.say();
	//user.run();
}
Copy the code

Please point out any questions