Quick start Spring

Spring

Realize the decoupling between classes: facilitate the management between classes

1. Light weight: it occupies less resources during operation, has high operation efficiency, and does not rely on other jar s

2. Decoupling: spring provides ioc control inversion, which enables the container to manage objects and their dependencies. The creation of objects was originally realized in the program code, but now it is completed by the container to realize the decoupling between objects

3.aop support

4. It can integrate various excellent frameworks (mybatis)

core

ioc

Di (as the technical implementation of ioc): dependency injection only needs the name of the object to use the object

spring uses the underlying reflection to create objects

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 the AOP idea of aspect oriented programming of Spring

In the idea of aspect oriented programming AOP, 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

Purpose of AOP

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.

Concepts in AOP
  • Pointcut
    On which classes and methods to cut in (where)
  • Advice
    What is actually done in the execution of the method (* * when: * * before / after the method / before and after the method) (* * what: * * enhanced functions)
  • Aspect
    Popular = popular + cut in point, what is the cut in point, what is the cut in point!
  • Weaving
    The process of adding facets to objects and creating proxy objects. (completed by Spring)
An example

In order to better illustrate the concept of AOP, let's take a practical example to illustrate:

In the above example, the core business of the charterer is to sign the contract and collect the rent. That's enough. The gray framed parts are repetitive and marginal things. Just give them to the intermediary. This is an idea of AOP: separate the focus code from the business code

Loading method

ApplicationContext: represents the container of spring. It is an interface with many implementations:
1. Classpathxmlapplicationcontext() - > scan xml for classpath to create container
2. Filesystemxmlapplicationcontext() - > read xml and create container according to file system path
3. Annotationconfigapplicationcontext - > create container according to annotation configuration class
4. Webxmlapplicationcontext() - > Web project

Profile based

Standard spring configuration class name: ApplicationContext xml

Managed acquisition

<?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="deom" class="xmlSpring.service.impl.DeomImpl"/>
    										<!--The prototype mode is loaded diligently and initialized once every call-->
    <bean id="deom1" class="xmlSpring.service.impl.DeomImpl" scope="prototype"/>
    <!--Will find use xml Loading external classes is relatively flexible-->
    <bean id="date" class="java.util.Date"/>
</beans>

Based on xml, you need an xml configuration file to configure the managed bean s

//Load xml file through classpath
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
Deom d= (Deom) ac.getBean("deom");
d.printHello();

DI injection

  1. Through property injection (set method must exist in bean, but property name may not exist)

    ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
    Student student = (Student) ac.getBean("student");
    System.out.println(student);
    
    <bean id="student" class="xmlSpring.bean.Student">
        <!--        Method of setting value      -->
        <property name="age" value="12"/>
        <!--        How to set properties     -->
        <property name="school" ref="school"/>
        <property name="name" value="Ma Daoyu"/>
    </bean>
    
    <bean id="school" class="xmlSpring.bean.School">
        <property name="name" value="Hunan Institute of Technology"/>
        <property name="age" value="100"/>
    </bean>
    
  2. Injection by construction method

    Student student1= (Student) ac.getBean("student1");
    System.out.println(student1);
    
    <bean id="student1" class="xmlSpring.bean.Student">
        <!--have access to name,index Or not declare  index It needs to be specified in the order of parametric construction    Do not declare that the position cannot be adjusted-->
        <constructor-arg name="age" value="1"/>
        <constructor-arg name="name" value="asd"/>
        <constructor-arg name="school" ref="school"/>
    </bean>
    
    <bean id="school" class="xmlSpring.bean.School">
            <property name="name" value="Hunan Institute of Technology"/>
            <property name="age" value="100"/>
     </bean>
    
  3. Automatic injection (only references can be injected automatically, not basic fields, such as String int)

    1.byName

        <bean id="student2" class="xmlSpring.bean.Student" autowire="byName">
            <!--        Method of setting value      -->
            <property name="age" value="12"/>
            <property name="name" value="Ma Daoyu"/>
        </bean>
    
        <bean id="school" class="xmlSpring.bean.School">
            <property name="name" value="Hunan Institute of Technology"/>
            <property name="age" value="100"/>
        </bean>
    

    student has a property named school. autowrite automatically injects the byname field name into the field named school in the configuration class

    1. ByType

      <bean id="student3" class="xmlSpring.bean.Student" autowire="byType">
          <!--        Method of setting value      -->
          <property name="age" value="12"/>
          <!--        How to set properties     -->
          <!--        <property name="school" ref="school"/>-->
          <property name="name" value="Ma Daoyu"/>
      </bean>
      
      <bean id="school" class="xmlSpring.bean.School">
          <property name="name" value="Hunan Institute of Technology"/>
          <property name="age" value="100"/>
      </bean>
      

      In student, there is an attribute of "school" in the field of "autowrite". Find schools of the same type through byType and inject automatically

Multi profile

If the project is too large, the configuration file will be large, so it should be written separately

import keyword

<!--    <import resource="classpath:spring/spring-School.xml"/>-->
<!--    <import resource="classpath:spring/spring-Student.xml"/>-->
<!-- When using wildcards,Note that the main configuration file name prevents conflicts with the generic configuration file,
	The upper layer of the configuration file must use a folder    Otherwise, it cannot be found   
-->
    <import resource="classpath:spring/spring-*.xml"/>

Annotation based

Annotation of declared bean (on class)

value attribute: defaults to the lowercase initial of the class name

@Component No clear role

@Service Use in business logic layer( service Layer)

@Repository Use in data access layer( dao Layer)

@Controller In the presentation layer, the declaration of the controller is used( C)

Annotation of injected bean

ps: automatically inject an object into the user object
​ @Autowired
​ user u

When there are two implementation classes, there are two ways to initialize the interface
	 * 1.Add to the implementation class@Primary
	 * 2.Add during variable initialization@Qualifier("Desired implementation class")

	 * 3.Use in variables resource(name=Class to implement)

@Autowired: from Spring provide    default byType

@Inject: from JSR-330 provide

@Resource: from JSR-250 Provide first use byName Principle reuse byType

Can be annotated in set In terms of methods and attributes, it is recommended to annotate attributes (at a glance, write less code).

java configuration class related annotations

1. Pure java

@Configuration Declaring the current class as a configuration class is equivalent to xml Formal Spring Configuration (required, can be empty) generally places implementation classes and provides main Method use//Use this class as an ioc container. The process is dependency injection (di) / / @ Configuration / / scan package / / @ ComponentScan(basePackages = {"Bean"})public class App{ 	 public static void main(String[] args) { 		//  Annotation parser function Tomcat loadclass(); Class - > read 		 ApplicationContext ctx = new AnnotationConfigApplicationContext(App.class); 		 System.out.println("container creation"); 		 Hello h = (Hello) ctx.getBean("h"); 		 h.sayHello(); 		}	}@ Bean annotation on the method declares that the return value of the current method is a bean, instead of the method in xml (on the method) @ Configuration declares that the current class is a Configuration class, in which the @ Component annotation is internally combined to indicate that this class is a bean (on the class) @ ComponentScan, which is used to scan components, It is equivalent to the combined annotation of @ WishlyConfiguration and @ ComponentScan in xml (on class), which can replace these two annotations

2. Configuration file

<!--Packet scanner--><context:component-scan base-package="noteSpring;xmlSpring"/>
ApplicationContext ac=new ClassPathXmlApplicationContext("noteSpring/applicationContext.xml");TestNote student = (TestNote) ac.getBean("testNote");

Read configuration file

Use $character

public class TestNote {    @Value("${name}")    private String name;//    @Autowired    private School s;}
<context:property-placeholder location="app.properties" file-encoding="utf8"/>

AOP (aspectj dependent)

[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-akpaoa5s0-1644158766294) (C: \ users \ FOX11 \ appdata \ roaming \ typora \ typora user images \ image-20201205110940321. PNG)]

[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qr0ljwxi-1644158766306) (C: \ users \ FOX11 \ appdata \ roaming \ typora user images \ image-20201205110903242. PNG)]

Execution sequence

Constructor (when initializing container) – >
@ postconstruct (when initializing the container, the constructor will execute as soon as it is finished) – >
@ around (code before executing method and pre enhanced. Processed() method) - >
@ before – >
Method of class – >
@ afterthrowing | @ afterreturning (with or without exception) – > abnormal stop
​ After()–>
The code after the @ around (. Processed () method. If there is an exception in the method, it will not run)

code implementation

Aspect class

@Aspect (added to the class to indicate that it is an aspect, and the class should be managed to the spring dependency as aspectj)

@org.aspectj.lang.annotation.Aspect@Componentpublic class Aspect {    /**     * Pre notice notes * requirements * 1 Public method public * 2 Method has no return value * 3 Method name custom * attribute value is a pointcut expression * features: * 1 Execute * 2 before the target method The execution result of the target method will not be changed * 3 It will not affect the execution of the target method * parameters: * JoinPoint: business method, the business method to add the aspect function * function: you can obtain the information during the execution of the method in the notification method, such as method name and method actual parameter * this parameter is given by the framework, not the parameter in the first position * * @ param jp     */    @Before("execution(public * AOP..*.add*(..))")    public void before(JoinPoint jp) {        System.out.println("=========Pre notification start============");        for (Object o : jp.getArgs()) {            System.out.println(o);        }        System.out.println("=========End of advance notice============");    }    /****     * Post notification * requirements * 1 Public method public * 2 Method has no return value * 3 Custom method name * 4 If the method has parameters, Object * attribute * 1 is recommended Value pointcut expression * 2 Returning self-defined variable, indicating the return value of the target method * the self-defined name must be the same as the formal parameter name of the notification method * characteristics * 1 Execute * 2 after the target method Can get the return value of the target method * 3 You can modify the return value * @ param res     */    @AfterReturning(value = "execution(public * AOP..*.add*(..))", returning = "res")    public void AfterReturning(JoinPoint jp, Object res) {        //System. Pass all values that do not change the original parameter out. Println ("====================================================================; System.out.println(res);        System.out.println("method information" + jp. Getsignature()); System.out.println("========================================================";} / * ** Surround notification * attribute * value pointcut expression * feature * 1 He is the most powerful notification * 2 Enhancements before and after the target method * 3 Control whether the target method is called * 4 Modify the execution result of the original target method and affect the final call result * * * * * return value * Object * it is equivalent to jdk dynamic agent * ProceedingJoinPoint is equivalent to method * * it is generally used for transaction processing * * * @ param PJP * / @ around (value = "execution (public * AOP.. *. Add * (..)") Public Object around (ProceedingJoinPoint PJP) throws throwable {Object result = null; System.out.println("===================================================="); / / the interface needs to inherit JoinPoint to obtain information if (12 = = integer. Valueof (PJP. Getargs() [0]. Tostring()) {result = PJP. Processed();} System.out.println("method information" + PJP. Getsignature()); System.out.println("===================================================================// If (result! = null) {result = 55;} return result;    }    /**     *  Requirements * 1 public     * 2. No return value * 3 Custom method name * 4 Method has an Exception, if any, jp * attribute * 1 Value pointcut expression * 2 The name of the Object throwing the Exception is the same as the passed in parameter name * @ param jp * @ param ex * / @ afterthrowing (value = "execution (public * AOP.. *. Add * (..)", Throwing = "ex") public void afterreturning (JoinPoint jp, Exception Ex) {/ / pass all values that do not change the original parameter System.out.println("===========================================); ex.printstacktrace(); System.out.println(" method information "+ jp. Getsignature()); system.out.println( "=================================================);} / * ** Requirements * 1 public     * 2. No return value * 3 Method name * custom attribute * 1 Value * features: * always executed * can be used to close resources * @ param jp * / @ after (value = "mypt()") public void after (JoinPoint jp) {/ / pass all values that do not change the original parameters System.out.println("========================================================================================= );         System.out.println("================================== end of final notice);} / * ** Define and manage pointcuts. If multiple pointcut expressions in your project are repeated * attribute * value pointcut expression * feature * in other notifications, you can use this method name instead of pointcut expression * / @ pointcut (value = "execution (public * AOP.. *. Add * (..)") public void mypt() {    }}
Implementation class of annotation class
@Configuration@ComponentScan(basePackages = "AOP")//Declaration used aop@EnableAspectJAutoProxypublic  class app {    public static void main(String[] args) {        ApplicationContext ac=new AnnotationConfigApplicationContext(app.class);        System.out.println(ac.getApplicationName());        add add = (AOP.add) ac.getBean(AOP.add.class);        add.add(12);    }}
Implementation of configuration file
    <bean id="add" class="AOP.impl.addImpl"/><!--    Declaration section-->    <bean id="as" class="AOP.Aspect"/><!--    Declare automatic proxy-->    <aop:aspectj-autoproxy />

In spring

If the class has a parent interface, the jdk proxy is automatically used

com.sun.proxy.$Proxy17

If not, the cglib proxy is automatically used

AOP.impl.addImpl$$EnhancerBySpringCGLIB$$4d366cd

Force cglib dynamic proxy

Annotation method

@EnableAspectJAutoProxy(proxyTargetClass = true)

Profile mode

<aop:aspectj-autoproxy proxy-target-class="true"/>

Two implementation methods of dynamic enhancement

jdk dynamic proxy and cglib dynamic proxy. The two methods exist at the same time and have their own advantages and disadvantages.

jdk dynamic agent Java Internal reflection mechanism

The bottom layer of cglib dynamic proxy is realized by asm

In general, the reflection mechanism is more efficient in the process of generating classes, while asm is more efficient in the related execution process after generating classes (you can cache the classes generated by asm to solve the problem of low efficiency in the process of generating classes by asm). It must also be noted that the application premise of jdk dynamic agent must be that the target class is based on a unified interface. Without the above premise, jdk dynamic agent cannot be applied. It can be seen that jdk dynamic agent has certain limitations. The dynamic agent realized by cglib, a third-party class library, is more widely used and has more advantages in efficiency..

(create a proxy object and automatically call back the interface method when calling the method)

jdk

public class App implements InvocationHandler{			private Object a;			public Object createCroxy(Object a) {			this.a=a;			//The first parameter is the class loader of the target class 			// The second parameter is the target class interface (template), because proxy needs to generate new proxy objects according to this template 			// The third parameter indicates the activation of the called method, automatic callback, and invoke in the InvocationHandler instance 			 return Proxy.newProxyInstance(a.getClass().getClassLoader(), 					 a.getClass().getInterfaces(), this); 					}				@ Override 		/**		 *  parameter 		 *  Parameters of the called method of the proxy object connection point 		 */		 public Object invoke(Object proxy, Method m, Object[] arg) throws Throwable { 			// Call the target class object first 			 Object o=m.invoke(a, arg); 						 if(m.getName().startsWith("add")) {  				// Equivalent to execution(* com.LightseaBlue.Spring..*.add * (..)) 				 System.out.println(""); 			}			 return o; 		}			}

test

UserDaoimpl ud=new UserDao();ud.addUser();	App a=new App();UserDaoimpl ud1=(UserDaoimpl) a.createCroxy(ud);ud1.addUser();ud1.sayName();

cglib

(the third-party jar package cglib nodep needs to be introduced)

	public class cglib implements MethodInterceptor{		private Object o;		public Object createProxy(Object o) {			this.o=o;			Enhancer e=new Enhancer();			//Set the parent class, that is, the interface class 			 e.setSuperclass(o.getClass()); 			// Set callback 			 e.setCallback(this); 			 return e.create(); 		}	@ Override 	/**	 *  Method parameters of proxy object class 	 */	 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 		 Object x=method.invoke(o, args); 		 System.out.println("post enhancement"); 		 return x; 	}}

Test

UserDaoimpl ud=new UserDao();cglib c=new cglib();UserDaoimpl ud1=(UserDaoimpl) c.createProxy(ud);ud1.addUser();

Spring transaction

1. Transaction isolation level: read uncommitted read committed repeatable read serialization

2. Timeout

3. Business communication behavior

Required supports required new (you must create your own transaction. If there is a current transaction pending, execute your own transaction first)

use

@EnableTransactionManagement enables the transaction to be placed in the startup class. In fact, it is enabled by default

Example: (usually on the service layer)

@Override@Transactional(rollbackFor = Exception.class)public boolean upDateUserStu(Integer uId, Integer uStu) throws Exception {    UpdateWrapper<TableUser> tableUserUpdateWrapper = new UpdateWrapper<>();    tableUserUpdateWrapper.lambda().eq(TableUser::getUId, uId).set(TableUser::getUStu, uStu);    boolean update = this.update(tableUserUpdateWrapper);    boolean updateAudioNameByUid = tableAudioNameService.updateAudioNameStuByUid(uId, uStu);    boolean b = update && updateAudioNameByUid;    if(!b){        throw new Exception("Rollback..");    }    return true;}

Little knowledge

Creation timing

When creating an object singleton
Diligent loading, singleton mode

alias mechanism

1. Add to comments value value     ps:server(value="s")2. @Bean	public server zz(){		return new server();	}   Applies to external packages that cannot modify the source code

When there is an implementation class, there are two ways to initialize the interface

  1. Add @ Primary to the implementation class (set class priority)
  2. Add @ Qualifier("desired implementation class") during initialization

Single or multiple cases?

Default singleton

When was it created?

Diligent loading - > lazy loading???

Initialize when creating container
By default, lazy loading is set for diligent loading. Add @ lazy (true) on the bean. When it is turned on, it is initialized when the object is obtained

The multi instance mode is also the initialization setting @ scope() when obtaining objects

    1. singleton Singleton mode,  There is only one instance in the global
  1. The prototype pattern will have a new instance each time it gets a Bean
  2. Request request means that a new bean will be generated for each HTTP request,
  3. The session scope indicates that a new bean will be generated for each HTTP request, and the bean is only valid in the current HTTP session
  4. The global session scope is similar to the standard HTTP Session scope,

Call parameterless constructor

To call a parameterless constructor, a parameterless constructor must be provided

  1. Are there more life cycle callback schemes??? init destroy
    @PostConstruct: gets called between the constructor and init method (if any) and executes only once.
    @PreDestory: the annotated method is executed after the destruction () method is called.

Keywords: Java JavaEE Spring

Added by brendandonhue on Sun, 06 Feb 2022 22:45:29 +0200