1. Introduction to spring
spring is a lightweight open source framework created by Rod Johnson in 2003 to solve the problem of high code coupling.
spring composition:
spring consists of 20 modules, the core of which are IOC and AOP
spring benefits:
- In the process of web application development, it can solve the problem that some objects run too slowly in the initial creation process.
- It is convenient to decouple, reduces code coupling and increases code maintainability.
- Based on the framework of MVC pattern integration, there are corresponding modules for each level of MVC, which is convenient for code writing.
- With test module, it is convenient for code testing.
- spring has no exclusive relationship with other frameworks, so it can integrate other frameworks better.
- Spring has nearly 20 modules, and each module can be extended better, and the control aspect is more flexible. It can be further developed on the basis of spring to form a new architecture or framework. Such as spring boot
Technology foreshadowing for learning spring
- reflex
- annotation
- Dynamic proxy
- XML analysis
- JAVA EE
2.IOC principle and basic use
IOC introduction:
It is the abbreviation of Inversion of Control. The application relies on the inversion idea to form an object container through reflection and factory mode. Users produce and control objects,
IOC principle:
- What is reversal? Under normal circumstances, when a servlet class needs to use a service object, it can use new directly. This is a forward rotation, and reverse is a container to control all the service objects. When a servlet needs to use a service, it only needs to wait passively for the injection
- Why reverse? In the coding process, we need to be as specific as possible. If class a needs to perform operation a, then we only need to perform operation a without any other operation. In the case of direct new, when performing some operations on behalf of class A, the creation and management of objects must be considered at the same time. When n classes need class A at the same time, if class a changes, then n classes calling class a need to be modified at the same time, which greatly increases the code coupling and is not conducive to development and maintenance.
- How to implement container: using reflection, annotation, xml technology.
public class Car{ private Wheel wheel; public void setWheel(){ this.wheel = wheel; } public void make(){ System.out.println("Wheel specifications:"+wheel); } } class Wheel{ private int size; public void setNum(int size){ this.size= size; } public String toString(){ return "radius"+size+"centimeter"; } } /*** 4. Object container */ class Container{ public static void main(String[] strs){ /*The path is obtained through xml or annotation*/ Class wheelClass = Class.forName("Wheel Class path"); Class carClass = Class.forName("Car Class path"); Car car = (Car)carClass.newInstance(); car.setWheel((Wheel)wheelClass.newInstance()); car.make(); } }
Basic use of IOC:
- Add jar package. In the spring project jar package, three cores must be added: beans, context, and core. If it is a web project, you must add the web jar package, and which of the other jar packages to add. Here is the pom.xml file
<!-- spring-core package --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- spring-context package --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- spring-beans package --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.3.RELEASE</version> </dependency>
- Write the User class to test the spring bean container
public class User { private int id; private String name; public User(){} public User(int id,String name){ this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
- Write spring.xml file or use annotation to configure spring related information
<?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 Three ways to create 1.Create with nonparametric construction 2.Create with static factory 3.Create with instance factory bean Scope of action scope="prototype" Multiple instances scope="singleton" Singleton mode, default //Parameter construction method attribute injection <constructor-arg name="id" value="1"></constructor-arg> set Method attribute injection <property name="id" value="1"></property> //Object attribute injection ref attribute --> <bean id="user" class="com.zy.bean.User"> <property name="id" value="1"></property> <property name="name" value="Zhang San"></property> </bean> <bean id="user1" class="com.zy.beanFactory.UserFactory" factory-method="getUserStatic"></bean> <bean id="userFactory" class="com.zy.beanFactory.UserFactory"></bean> <bean id="user2" factory-bean="userFactory" factory-method="getUser"/> <bean id="user3" class="com.zy.bean.User" scope="singleton"></bean> <bean id="user4" class="com.zy.bean.User" scope="prototype"></bean> </beans>
- If it is a web project, you need to modify web.xml and configure the spring listener. The listener is used to listen to the creation of ServletContext class objects. When the server creates the ServletContext object, it creates all bean s configured in spring, and puts the pressure of creating objects to tomcat to deal with, so as to prevent the problem that the first creation time is too slow.
- Write test class
public class SpringTest { public static void main(String[] args) { //Get spring profile ApplicationContext context = new ClassPathXmlApplicationContext("fill in spring Profile path"); //Nonparametric construction creation User user = (User) context.getBean("user"); System.out.println(user); //Static factory creation User user1 = (User) context.getBean("user1"); System.out.println(user1); //Instance factory creation User user2 = (User) context.getBean("user2"); System.out.println(user2); //Scope of action: single case User user3 = (User) context.getBean("user3"); user3.setId(4); user3.setName("Zhao Liu"); System.out.println("For the first time:---------------------"+user3); User user4 = (User) context.getBean("user3"); System.out.println("The second time:---------------------"+user4); System.out.println("---------------------------------------------"); //Scope of action: single case User user5 = (User) context.getBean("user4"); user5.setId(4); user5.setName("Zhao Liu"); System.out.println("For the first time:---------------------"+user5); User user6 = (User) context.getBean("user4"); System.out.println("The second time:---------------------"+user6); /** * IOC(The difference between inversion of control / creation of objects) and DI (dependency injection) * Relationship: dependency injection cannot exist alone. It needs to be done on the basis of IOC */ } }
3.AOP principle and simple use
AOP introduction:
Aspect Oriented Programming is short for aspect oriented programming. Generally speaking, vertical thinking is adopted in programming. For example, when a tiger eats, it needs to determine what needs to be done before eating and what needs to be done after eating;
- Core concepts of AOP: crosscutting concern, aspect, join point, pointcut, advice, target object, weave, introduction
- Why use AOP? During the epidemic, most people's life track is getting up - > playing mobile phone - > eating When you get up, you play with your mobile phone. If you only use vertical thinking, you will write play with your mobile phone in the method of getting up. But after the epidemic, everyone's life trajectory will change, so we need to change the way everyone gets up. Therefore, it is necessary to use aspect oriented programming to specify the things to be done before and after getting up with one class or several classes. After modification, it is not necessary to modify all people's getting up methods.
- What are the benefits of using AOP? Code decoupling reduces the workload of code maintenance or modification.
AOP principle:
Through the way of dynamic agent, the control of operation before and after the method is realized
/*** * This interface is used for dynamic proxy, which is used when creating proxy objects */ public interface Person{ public void getUp(); } /*** * Classes to be proxied */ class Student implements Person{ public void getUp(){ System.out.println("Get up"); } } /*** * Class for proxy Student */ class StuProxy implements InvocationHandler{ private Object obj; public StuProxy(Object obj){ this.obj = obj; } //This method does not need to be called by itself. When the system calls the class method being proxied by this class, the system automatically calls this method public Object invoke(Object proxy, Method method, Object[] args )throws Throwable{ System.out.println("getUp Dynamic agent before"); return method.invoke(obj,args); } } /*** * Test class */ Class AopTest{ public static void main(String[] strs){ Person person = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(),new Class[]{Person.class},new StuProxy(new Student())); person.getUp(); } }
Basic use of AOP:
- To import the jar package, you need to add the spring AOP jar package and aspectj jar package on the basis of IOC
- Interface
public interface Person{ public void getUp(); }
- Implementation class
public class Student implements Person{ public void getUp(){ System.out.println("get up...."); } }
- Class aop
public class Aspectj { public void getUpAfter(){ System.out.println("getUpAfter method...."); } }
- spring.xml configuration
< bean id = "stu" class = "classpath" > < bean > < bean id = "AspectJ" class = "classpath" > < bean > <aop:config> <! -- AOP: the aspectj class needs to be filled in the aspect, and the detection method call -- > <aop:aspect ref="aspectj"> <! -- AOP: pointcut configuration method path to be monitored -- > < AOP: pointcut id = "getup" expression = "execution (* method path" / > <! -- which method in the listening class needs to be called when listening method calls -- > <aop:after method="getUpAfter" pointcut-ref="getUp" /> </aop:aspect> </aop:config>
- Test class
ApplicationContext context = new ClassPathXmlApplicationContext("spring Profile path"); Person person = context.getBean("stu"); person.getUp();
Well, there are too many things, so here are just some basic operations that can't be performed any more. There are other spring modules and detailed analysis of IOC and AOP in the back
I hope we can learn and progress together.
Please point out where the writing is not good