Spring framework
1. What is Spring?
The Spring framework is an open source J2EE application framework, initiated by Rod Johnson , and it is a lightweight container that manages the life cycle of beans. Spring solves many common problems encountered by developers in J2EE development and provides powerful functions such as IOC, AOP and Web MVC
1.1 Advantages of spirng
1. Facilitate decoupling and simplify development
Through the IoC container provided by Spring, we can hand over the dependencies between objects to Spring to control, avoiding excessive program coupling caused by hard coding. With Spring, users no longer need to write code for low-level requirements such as single-instance mode classes and property file analysis, and can focus more on upper-level applications.
2. AOP programming support
The AOP function provided by Spring facilitates aspect-oriented programming. Many functions that are not easy to implement with traditional OOP can be easily handled by AOP.
3. Declarative transaction support
In Spring, we can get rid of the monotonous and boring transaction management code, and flexibly manage transactions in a declarative way to improve development efficiency and quality.
4. Convenient for program testing
You can use non-container-dependent programming for almost all testing work. In Spring, testing is no longer an expensive operation, but something that can be done at hand. For example: Spring supports Junit4, so you can easily test Spring programs through annotations.
5. Conveniently integrate various excellent frameworks
Spring does not exclude various excellent open source frameworks. On the contrary, Spring can reduce the difficulty of using various frameworks. Spring provides direct support for various excellent frameworks (such as Struts, Hibernate, Hessian, Quartz), etc.
6. Reduce the difficulty of using Java EE API
Spring provides a thin encapsulation layer for many difficult-to-use Java EE APIs (such as JDBC, JavaMail, remote calls, etc.). Through Spring's simple encapsulation, the difficulty of using these Java EE APIs is greatly reduced.
2. Spring core container
The Spring container will be responsible for controlling the relationship between the programs, rather than directly controlled by the program code. Spring provides us with two core containers, namely BeanFactory and ApplicationContext
2.1 BeanFactory
When creating a BeanFactory instance, you need to provide detailed configuration information of the container managed by Spring. This information is usually managed in the form of an XML file. The syntax for loading configuration information is as follows:
BeanFactory beanFactory =
new XmlBeanFactory(new FileSystemResource("F: /applicationContext.xml"));
2.2 ApplicationContext
Inheriting the BeanFactory, not only the realized functions, but also the ability to increase internationalization, resource access, event propagation, etc.
Common implementation class
ClassPathXmlApplicationContext The main user obtains the configuration under the resource path
//大多数使用这种方式
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean01.xml");
Student student = applicationContext.getBean(Student.class);
FileSystemXmlApplicationContext mainly obtains the configuration of the absolute path
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src\\main\\resources\\bean01.xml");
Student student = applicationContext.getBean(Student.class);
3. Project construction
3.1 Create a java project and introduce dependencies
<properties>
<!--在当前pom 或者父类pom 中声明属性 -->
<spirng.version>5.0.16.RELEASE</spirng.version>
</properties>
<!-- 引入spring 核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spirng.version}</version>
</dependency>
3.2 Create spring configuration file in resource
<?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>就是一个对象
-->
<!-- 一个bean 就是一个对象 就是让容器创建一个对象-->
<bean id="student" class="com.yth.entity.Student">
<!-- 设置属性值-->
<property name="id" value="100"></property>
<property name="name" value="赵四"></property>
</bean>
</beans>
3. Test
@Test
public void Test01(){
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("src\\main\\resources\\bean01.xml"));
Student student = beanFactory.getBean(Student.class);
System.out.println(student);
}
@Test
public void Test02(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean01.xml");
Student student = applicationContext.getBean(Student.class);
System.out.println(student);
}
@Test
public void Test03(){
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src\\main\\resources\\bean01.xml");
Student student = applicationContext.getBean(Student.class);
System.out.println(student);
}
4. Inversion of control and dependency injection
4.1 Inversion of Control IOC
Inversion of control, IOC. After using the Spring framework, the instance of the **object is no longer created by the caller, but by the Spring container. The **Spring container will be responsible for controlling the relationship between programs, rather than directly controlled by the caller's program code . In this way, control is transferred from the application code to the Spring container, and the control is reversed, which is the inversion of control.
** The power to create objects to the container , we just need to tell the container you need those common objects on it, and the container will always hold the object, the object lifecycle management, through getBean () ** Gets the object
Self-built
// 自己手动创建对象
Student student = new Student();
Container creation
// spring容器获取对象步骤:
// 1.bean.xml 声明要创建的对象
// 2.使用BeanFactory 的子类 去加载 bean.xml 配置 ,按照配置文件创建 bean对象,并且放置在容器中
// 3. getBean(Student.class); 使用getBean 根据类型获取
4.2 Dependency Injection DI
The full name of DI is Dependency Injection, which is called Dependency Injection in Chinese
From the perspective of the Spring container, the Spring container is responsible for assigning dependent objects to the caller's member variables, which is equivalent to injecting the instance that it depends on for the caller. This is Spring's dependency injection.
Dependency injection is mainly used to control the dependencies between objects in the container
<!-- 声明一个id为studentDao的实例 -->
<bean id="studentDao" class="com.yth.dao.impl.StudentDaoImpl"></bean>
<!-- 通过ref="iStudentDao" 容器中idiStudentDao 的对象 设置到StudentServiceImpl 对应studentDao 属性内 -->
<bean id="studentService" class="com.yth.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
test
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean01.xml");
StudentService studentService = (StudentService) applicationContext.getBean("studentService");
// 不需要手动控制依赖 使用容器控制依赖关系
// studentService.setStudentDao(StudentDao);
Student student = studentService.getStudentByID(10);
System.out.println(student);
5. Bean configuration
5.1 What is Bean?
If you regard Spring as a large factory, then the Bean in the Spring container is the product of the factory. If you want to use this factory to produce and manage Beans, you need to tell it in the configuration file which Beans it needs, and how to assemble these Beans together.
The essence of Bean is the object in Java, and the Bean in Spring is actually a reference to the entity class to produce Java class objects, so as to realize the production and management of Bean.
5.2 Bean properties
Bean configuration uses xml configuration. The root element of the XML configuration file contains multiple sub-elements. Each sub-element defines a Bean and describes how the Bean is assembled into the Spring container. The common attributes of elements are shown in the following table:
note:
id must be unique in Bean, and name can have multiple
<!-- 一个bean 就是一个对象 就是让容器创建一个对象
id 容器创建对象的唯一标识
name 也为对象取一个标识 name name可以有多个 使用,或者; 分割
-->
<bean id="student" name="zhaosi,si" class="com.yth.entity.Student">
<!-- 设置属性值-->
<property name="id" value="100"></property>
<property name="name" value="赵四"></property>
</bean>
//根据属性名获取student
@Test
public void Test05(){
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src\\main\\resources\\bean01.xml");
Student student = (Student) applicationContext.getBean("zhaosi");
System.out.println(student);
Student student2 = (Student) applicationContext.getBean("si");
System.out.println(student2);
}
5.3 Instantiation of Bean
In Spring, if you want to use the Bean in the container, you also need to instantiate the Bean. There are three ways to instantiate Bean, namely constructor instantiation, static factory instantiation and instance factory instantiation (the most commonly used is constructor instantiation).
5.3.1 Default no-parameter construction method
The container calls the no-argument constructor to create the object
5.3.2 Static factory instance method
The advantage is: you can customize the created object , and give the object to the container management
Create a static factory
package com.yth.Factory;
import com.yth.entity.Student;
/**
* @author yth
* @date 2020/10/19 - 20:33
*/
public class StaticStudentFactory {
/**
* 自定义 Student 对象的创建
* 获取了创建对象的权力
* @return
*/
public static Student createStudent(){
Student student = new Student();
// 比如name 去网络查询 数据库查询
student.setName("广坤");
student.setId(101);
return student;
}
}
Declare objects created using the factory
<!--
bean 像容器声明创建对象 此时创建对象是由静态工厂创建 而不是容器直接创建
class="com.qfedu.factory.StaticStudentFactory" 创建对象的静态工厂
factory-method="createStudent" 制定创建对象的静态工厂方法
-->
<bean id="student" class="com.yth.Factory.StaticStudentFactory" factory-method="createStudent"></bean>
Test acquisition object
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:Factory\\StaticStudentFactory.xml");
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);
5.4.3 Instance factory instantiation
The role is the same as the static factory instantiation
Create an instance factory
package com.yth.Factory;
import com.yth.entity.Student;
/**
* @author yth
* @date 2020/10/19 - 20:48
*/
public class StudentFactory {
public Student creatStudent(){
Student student = new Student();
// 自定义初始化 student
student.setName("xiaoming");
student.setId(1000);
return student;
}
}
Declare an instance factory and use the instance factory to create objects
<!-- 声明实例工厂 创建实例工厂对象 -->
<bean id="studentFactory" class="com.yth.Factory.StudentFactory"></bean>
<!--
通过实例工厂创建对象
factory-bean="studentFactory" 引用实例工厂
factory-method="creatStudent" 调用实例工厂的 creatStudent 创建自定义的Student对象 并放置到容器中
-->
<bean id="student" factory-bean="studentFactory" factory-method="creatStudent"></bean>
test
//实例工厂创建bean
@Test
public void Test07(){
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:Factory\\StudentFactory.xml");
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);
}
5.4.4 Summary
The role of static factory instantiation and factory instantiation is to create objects with self-defined requirements, mainly used for the initial connection of the dao layer (to solve the problem of MySQL password encryption)