Spring Frameworkd (Chinese
1. Overview (Spring5)
-
Spring
-
The IOC container
Inversion of control. Leave the object creation process to Spring to manage
- Aop container
Section-oriented enhancements without modifying source code.
-
JdbcTemplate
-
Transaction management
-
Spring5 new features
1.1 introduction
Spring boot
-
A fast developing scaffold
-
You can quickly develop individual microservices based on it
-
Convention greater than configuration!!
SpringCloud
- Based on Spring Boot implementation
Most companies now use SpringBoot for rapid development. The prerequisite for learning it is to learn Spring and SpringMVC.
Disadvantages of Spring development:
Configuration is very cumbersome, known as “configuration hell”.
The official website, GA stands for stable version.
Repo. Spring. IO/release/org…
5.2.6
To understand:
Use XML configuration files for configuration. We used to create objects using new, but now we use beans.
To create a Spring project, you need to import only five packages at a basic level. Spring includes four JARS for Core, Context, Beans, and expression, as well as one commons-logging JAR.
Write an introductory case.
When I introduced Test @test, I was prompted to download junit dependencies from Maven. Then I noticed from Settings that the Maven configuration had changed to the previous default and changed it back to the Maven address and repository that I had downloaded and configured. And then it was introduced very quickly.
2. The IOC container
2.1 Concepts and Principles
Inversion of control. Inversion of Control
OOP is a design principle used to reduce coupling between computer code
The most common approach is called Dependency injection (DI), and another is called Dependency lookup.
Previous practice:
-
UserDao interface
-
UserDaoImpl implementation class
-
UserService Business interface
-
UserServiceImpl Business implementation class
In the previous business, the needs of users may affect our original code, so we need to modify the original code according to the needs of users. If the code volume is very large, the modification cost is very high.
The use of a Set interface implementation has been revolutionized.
-
Before, it was the program that created the object! Control rests with the programmer
-
With Set injection, the program is no longer active, but passively accepting objects. The initiative is given to the user.
The idea is inversion of control, essentially solving the problem so that programmers don’t have to manage object creation, the system becomes much less coupled and can focus more on business implementation.
This is the prototype of IOC.
The IOC nature:
When we use object-oriented programming, the creation of objects and the dependencies between objects are completely hard-coded in the program, and object creation is controlled by the program itself. Inversion of control transfers object creation to a third party.
Similar to the factory design pattern.
Somebody else is going to use an example. The old way is you seal a class, you create an instance in it. You give it to someone else when they use it. You have to change your new code if someone else wants to use another instance.
Now someone else wants to use an instance, he passes you a parameter (unsolicited to tell you what he wants to use), and your program gives him an instance based on that parameter.
IOC is at the heart of the Spring framework and can be implemented in a variety of ways, from XML configuration to annotations, and with new versions of Spring, IOC can be implemented with zero configuration.
The Spring container first reads the configuration file during initialization, and creates and organizes objects according to the configuration file or metadata into the container. When the program is used, the required objects are extracted from the IOC container.
Underlying principles of IOC:
XML parsing + factory schema + reflection.
Reflection: get the bytecode file of the class, class file.
The IOC process:
- XML configuration file that configures the objects created
- There are service classes and DAO classes, creating factory classes
Class.forName(classValue);
class UserFactory {
public static UserDao getDao(a) {
String classValue = classAttribute values; / / XML parsing
Class clazz = Class.forName(classValue); // create an object by reflection
return(UserDao)clazz.newInstance(); }}Copy the code
IOC interface
1. IOC thought is based on IOC container, and the bottom of IOC container is the factory
2. Spring provides two ways to implement IOC :(two interfaces)
-
BeanFactory
IOC container basic implementation, Spring internal use interface, not provided for developers to use.
Features: No object is created when the configuration file is loaded. Objects are created when the object is fetched (used) (getBean).
-
ApplicationContext
A subinterface of the BeanFactory interface that provides more powerful functionality and is generally used by developers.
Features: The configuration file object is created when the configuration file is loaded.
The second way is generally used. According to?
The first one looks like lazy loading, saves resources and should be better.
However,
We usually complete these time-consuming and resource-consuming operations at the start of our project. Objects are created during server startup, not when.
3. The ApplicationContext interface has implementation classes.
Such as FileSystemXmlApplicationContext and ClassPathXmlApplicationContext. The former is the disk path and the latter is the package classpath.
Summary: Inversion of control is a way to produce or obtain a specific object through a description (XML or annotations) and through a third party. Inversion of control in Spring is implemented by the IOC container through dependency injection (DI)
2.2 IOC operation Bean management
- What is Bean management?
Two operations — 1. Spring creates the object; 2. Spring injects properties
- Bean management operates in two ways
- Implementation based on XML configuration file
- Annotation based implementation
2.2.1 Based on XML
Create objects based on XML
<bean id="user" class="com.atguigu.spring5.User"></bean>
Copy the code
1st. Use the bean tag in the Spring configuration file to add the corresponding properties to the tag to achieve object creation
There are many properties in the bean tag. Here are some common properties.
-
Id attribute: not the name of the object, but an alias, unique identifier
-
Class property: Create the full path of the object class (package classpath)
-
The name attribute: An early attribute that acts like an ID. However, special characters can be added to name.
By default, the no-parameter constructor is executed when the object is created.
Injection of attributes based on XML
1st. DI: Dependency injection, which is to inject properties.
One: use the set method for injection. book.setName(“args”)
The second is injection via a constructor with arguments. new Book(“args”)
The former configuration file is used for:
<bean id="book" class="com.atguigu.spring5.Book">
<property name="bname" value="Easy tendons"></property>
</bean>
Copy the code
The property injection is done with property, where name is the property name (member variable name) and value is the injected value.
The latter configuration file does :(inject with parameter construction)
<bean id="order" class="com.atguigu.spring5.Orders">
<constructor-arg name="oname" value="Computer"></constructor-arg>
<constructor-arg name="address" value="China"></constructor-arg>
</bean>
Copy the code
Simplify the above method:
P namespace injection simplifies xmL-based configuration. (Don’t use much, understand can be)
- Literal:
Set a null value
<property>
<null />
</property>
Copy the code
Property value contains special characters
For example, an Angle bracket might be recognized as a /
-
Escape Angle brackets, escape symbol: < >
-
Write the special symbol content to CDATA
<property>
<value><! [CDATA [< < Nanking > >]] ></value>
</property>
Copy the code
<! [CDATA [content]] >
- Inject properties – External beans
- Injection properties – inner beans and cascading assignments
- External bean injection:
Calling daOs through the Service layer is the process of introducing external beans.
1ST creates two classes: service and DAO.
2nd calls dao’s methods in service.
3rd Set this parameter in the Spring configuration file.
<! Create service and DAO objects -->
<! -- External bean mode -->
<bean id="userService" class="com.phsite.service.UserService">
<! Insert userDao object name= attribute name ref attribute, create userDao object bean tag ID value. (The one below) -->
<property name="userDao" ref="userDaoImpl"></property>
</bean>
<bean id="userDaoImpl" class="com.phsite.dao.UserDaoImpl"></bean>
Copy the code
- Internal bean injection
1ST One-to-many relationships: Departments and employees
A department has multiple employees, and an employee belongs to a department.
The department is one, the staff is many.
2nd represents a one-to-many relationship between entity classes, with the department of an employee represented by an attribute of an object type.
3rd Set this parameter in the Spring configuration file
<! -- Internal bean mode -->
<bean id="emp" class="com.phsite.bean.Emp">
<property name="ename" value="Lucy"></property>
<property name="gender" value="Female"></property>
<property name="dept">
<bean id="dept" class="com.phsite.bean.Dept">
<property name="dname" value="Security Department"></property>
</bean>
</property>
</bean>
Copy the code
Summary: The bean tag creates the object. External benA creates a new bean outside of a bean and introduces it in a property using the ref attribute. An inner bean is a bean written directly inside a property.
- Cascade assignment
Method 1:
<! -- Cascade assignment -->
<bean id="emp" class="com.phsite.bean.Emp">
<property name="ename" value="Lucy"></property>
<property name="gender" value="Female"></property>
<! -- Cascade assignment -->
<property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="com.phsite.bean.Dept">
<property name="dname" value="Finance Department"></property>
</bean>
Copy the code
Method 2:
<! -- Cascade assignment -->
<bean id="emp" class="com.phsite.bean.Emp">
<property name="ename" value="Lucy"></property>
<property name="gender" value="Female"></property>
<! -- Cascade assignment -->
<property name="dept" ref="dept"></property>
<property name="dept.dname" value="Technical Department"></property>
</bean>
<bean id="dept" class="com.phsite.bean.Dept">
<property name="dname" value="Finance Department"></property>
</bean>
Copy the code
We must generate a get method for the DEPT property in the Emp class, otherwise it will fail to get the value.
XML injection collection attributes
Such as arrays, lists, maps, etc.
-
Inject array type properties
-
Inject the List collection type attribute
-
Inject Map collection type attributes
-
Sets the object type value in the collection.
-
<! Create multiple course objects --> <bean id="course1" class="com.phsite.collectionType.Course"> <property name="cname" value="Spring5 framework"></property> </bean> <bean id="course2" class="com.phsite.collectionType.Course"> <property name="cname" value="MyBatis framework"></property> </bean> Copy the code
-
<property name="courseList"> <list> <ref bean="course1"></ref> <ref bean="course2"></ref> </list> </property> Copy the code
-
-
Extract (make publicly available) the injected parts of the collection.
- Introduce a new namespace util in the Spring configuration
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
Copy the code
- Use the util tag to complete list collection injection
<! Extract list collection type property injection, public part -->
<util:list id="bookList">
<! <ref></ref>-->
<value>Yi jin jing</value>
<value>Sun alkaloids</value>
</util:list>
<! - use - >
<bean id="book" class="com.phsite.collectionType.Book">
<property name="list" ref="bookList"></property>
</bean>
Copy the code
Four FactoryBean.
- Spring has two types of beans, plain beans and factory beans
- Plain beans: Define the bean type as the return type in the configuration file
- Factory Beans: Define bean types in configuration files that are different from return types
Step 1: create a class that acts as a FactoryBean and implements the interface FactoryBean
Step 2: Implement the method in the interface and define the returned bean type in the implemented method.
The Instance:
Writing:
public class myBean implements FactoryBean<Course> {
// Define the method that returns the Bean
@Override
public Course getObject(a) throws Exception {
Course course = new Course();
course.setCname("abc");
return course;
}
@Override
publicClass<? > getObjectType() {return null;
}
@Override
public boolean isSingleton(a) {
return false; }}Copy the code
Configuration:
<bean id="mybean" class="com.phsite.factorybean.myBean">
</bean>
Copy the code
Testing:
@Test
public void test3(a) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean3.xml");
Course course = context.getBean("mybean", Course.class);
System.out.println(course);
}
Copy the code
Scope of bean
In Spring, beans are singleton objects by default!! .
(You created two objects with the same address!!)
- How to set single-instance or multi-instance
The Spring configuration file has a property in the bean tag that sets single-instance or multi-instance
- The scope attribute
The first value, the default, singleton, represents a singleton object
The second value, prototype, indicates a multi-instance object
Others include request and session.
<bean id="book" class="com.phsite.collectionType.Book" scope="prototype">
<property name="list" ref="bookList"></property>
</bean>
Copy the code
- Singleton and Prototype
-
The former is single-instance, the latter multi-instance
-
When you set scope to Singleton, you will be given a singleton when the Spring configuration file is loaded.
-
When scope is set to Prototype, instead of creating objects when the Spring configuration file is loaded, multi-instance objects are created when the getBean method is called.
7. Bean life cycle
- What is the life cycle?
The process from object creation to object destruction.
-
The life cycle of the bean
- Create bean instance through constructor (no-argument constructor)
- Set values for bean properties and references to other beans (call the set method)
- Invoke the bean’s initialization method (need to configure initialization method in configuration file)
- The bean is ready to use. (Object got)
- When the container is closed, the bean’s destruction method is called. (Destruction method needs to be configured in configuration file)
-
show
public class Orders {
// No argument constructor
public Orders(a) {
System.out.println("Step 1, create the bean instance by performing a no-argument construct.");
}
private String oname;
public void setOname(String oname) {
System.out.println("Step two, call the set method to set the property value.");
this.oname = oname;
}
// Create an initialization method to execute
public void initMethod(a) {
System.out.println("Step three, execute the initialization method.");
}
// Create a destruction method
public void destroyMethod(a) {
System.out.println("Step five, method of performing destruction."); }}Copy the code
<bean id="orders" class="com.phsite.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value="Mobile phone"></property>
</bean>
Copy the code
@Test
public void testBean4(a) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean4.xml");
Orders orders = context.getBean("orders", Orders.class);
System.out.println("Step 4, get the created bean instance object");
System.out.println(orders);
// Manually let the bean instance be destroyed.
((ClassPathXmlApplicationContext) context).close();
}
Copy the code
Effect:
The first step is to perform a no-argument construct, creating the bean instance the second step, the callsetMethod set the property value in step 3, perform initialization method step 4, get the created bean instance object com.phsite.bean.Orders@1ca3b418 in step 5, perform destruction methodCopy the code
Note: the final close destructor is ClassPathXmlApplicationContext class. ApplicationContext is not available.
- The bean’s post-processor, the bean’s life cycle is a total of seven steps.
In addition to those five steps, there are two more
-
Create bean instance through constructor (no-argument constructor)
-
Set values for bean properties and references to other beans (call the set method)
-
The bean instance is passed to the rear of the bean postProcessBeforeInitialization processor
-
Invoke the bean’s initialization method (need to configure initialization method in configuration file)
-
The bean instance is passed to the rear of the bean postProcessAfterInitialization processor
-
The bean is ready to use. (Object got)
-
When the container is closed, the bean’s destruction method is called. (Destruction method needs to be configured in configuration file)
-
Presentation:
Create a class that implements the interface BeanPostProcessor and creates a post-processor.
public class myBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Methods executed before initialization");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Methods executed after initialization");
returnbean; }}Copy the code
<bean id="orders" class="com.phsite.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value="Mobile phone"></property>
</bean>
<! -- Configure the rear processor -->
<bean id="myBeanPost" class="com.phsite.bean.myBeanPost"></bean>
Copy the code
The first step is to perform a no-argument construct, creating the bean instance the second step, the callsetMethod sets the property value in the third step of the method performed before initialization, executes the initialization method in the fourth step of the method performed after initialization, obtains the created bean instance object com.phsite.bean.Orders@74e28667 in the fifth step, executes the destruction methodCopy the code
XML auto-assembly
(This is rarely used in practice, mostly as annotations, but be aware that XML can also be auto-assembled.)
Previously, we wrote the value and ref attributes in the configuration file to manually assemble.
You don’t need to write this configuration now
- What is automatic assembly?
Spring automatically injects matching property values based on the specified assembly rule (property name or property type).
- demo
Auto assemble by attribute name
<! -- Manual assembly -->
<! -- <bean id="emp" class="com.phsite.autowire.Emp">-->
<! -- <property name="dept" ref="dept"></property>-->
<! -- </bean>-->
<! -- <bean id="dept" class="com.phsite.autowire.Dept"></bean>-->
<! The bean id value is the same as the class attribute name. ByType is injected byType.
<bean id="emp" class="com.phsite.autowire.Emp" autowire="byName"></bean>
<bean id="dept" class="com.phsite.autowire.Dept"></bean>
Copy the code
9. External properties file
One property for each property, that’s a lot of configuration to write.
(Introducing druid dependencies.)
- Configure the database information directly
- Configure the druid connection pool
- Introduction of druid connection pool dependency JAR packages.
<! Configure connection pool directly -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
Copy the code
- Import an external properties file to configure the database connection pool
I. Create external properties file, properties file, write database information
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=root
Copy the code
Notice, the left-hand side of the equals sign is arbitrary. Naming conflicts can be avoided with prop. XXX
ⅱ. Add the external properties file to the Spring configuration file
- Introduce the context namespace
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
Copy the code
- Use tag import in the Spring configuration file
<! -- Import external properties file -->
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${prop.driverclass}"></property>
<property name="url" value="${prop.url}"></property>
<property name="username" value="${prop.username}"></property>
<property name="password" value="${prop.password}"></property>
</bean>
Copy the code
We typically write the database configuration in a Properties file and import it in XML for configuration.
2.2.2 Based on annotations
-
What is annotated
- Annotations are code specific markers. Format:
@ Annotation name (attribute name =xx, attribute value = XXX,...)
- Using annotations, annotations can be applied to classes, methods, and properties
- The purpose of using annotations: to simplify XML configuration
- Annotations are code specific markers. Format:
-
Spring provides annotations for creating objects in Bean management
- @Component, common annotations.
- @service, usually used in the Service layer
- @Controller, generally used in the external (Web) layer.
- @repository, for the DAO (persistence) layer.
The above four annotation functions are the same and can be used to create bean instances.
- Object creation based on annotations
The first step is to introduce dependencies
Spring – AOP JAR package.
Step 2: Enable component scanning
Tell the Spring container which class I want to annotate. You can’t annotate without opening it.
<! 1. If multiple packages are scanned, separate them with commas (,). 2. Scan package upper directory -->
<! -- <context:component-scan base-package="com.phsite.dao, com.phsite.service"></context:component-scan>-->
<context:component-scan base-package="com.phsite"></context:component-scan>
Copy the code
The third step is to create the class and add the create object annotation to the class
// The value attribute can be omitted in the annotation
// The default value is the class name, starting with a lowercase letter
// UserService --> userService
@Component(value = "userService") // and
public class UserService {
public void add(a) {
System.out.println("service add...."); }}Copy the code
- Details of enabling component scanning
After we write the scan path to the parent directory, it will scan all by default.
We want to do some scanning and some not scanning, there are some configurations that can be done.
<! -- example 1 use-default-filters="false" means that it now does not use the default filter, We're going to use our own filter context:include-filter to set what to scan and this is the class that sets the scan annotation as Controller, not the ones with other annotations. -->
<context:component-scan base-package="com.phsite" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<! -- Example 2 Context :exclude-filter sets which content is not scanned -->
<context:component-scan base-package="com.phsite">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
Copy the code
- Implement attribute injection based on annotation
- @Autowired
Auto-assemble (inject) based on the property type.
The first step is to create the Service and DAO objects, adding annotations to both classes to create the objects
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void add(a) {
System.out.println("dao add."); }}Copy the code
The second step is to inject dao objects into the Service, add DAO type attributes to the Service class, and use annotations on the attributes
// The value attribute can be omitted in the annotation
// The default value is the class name, starting with a lowercase letter
// UserService --> userService
@Service(value = "userService") // and
public class UserService {
// Define DAO type attributes
// There is no need to add the set method
// Add an injection attribute annotation
@Autowired // Inject by type
private UserDao userDao;
public void add(a) {
System.out.println("service add...."); userDao.add(); }}Copy the code
- @Qualifier
Inject by attribute name.
This annotation is used in conjunction with Autowired.
@Service(value = "userService") // and
public class UserService {
// Define DAO type attributes
// There is no need to add the set method
// Add an injection attribute annotation
@Autowired // Inject by type
@Qualifier(value = "userDaoImpl1") // Inject by name
private UserDao userDao;
public void add(a) {
System.out.println("service add...."); userDao.add(); }}Copy the code
@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao{
@Override
public void add(a) {
System.out.println("dao add."); }}Copy the code
As long as “value” matches the name.
- @Resource
You can inject by type or by name.
The resource annotations were not found at the beginning. Because of the lack of javax.annotation dependency. It’s not in Spring, it’s in Javax. Spring officially recommends using the preceding two.
@Resource(name = "userDaoImpl1")
private UserDao userDao;
Copy the code
- @Value
Inject normal type attributes
@Value(value = "abc")
private String name;
Copy the code
- Full annotation development
No configuration files.
ⅰ. Create a configuration class to replace the XML configuration file.
@Configuration // As a configuration class instead of an XML configuration file
@ComponentScan(basePackages = {"com.phsite"})
public class SpringConfig {}Copy the code
ⅱ. Write test classes
@Test
public void testService2(a) {
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringConfig.class);
// The loading configuration class has changed
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
Copy the code
SpringBoot is essentially Spring. In practice, this is usually done based on SpringBoot.