Spring Basics
01 Introduction to Spring
1.1, Spring family
-
Official website: https://spring.io, from the official website we can roughly understand:
- What Spring can do: It is used to develop web, microservices, and distributed systems. These three pieces alone account for
more than 90% of JavaEE development. - Spring is not a single technology, but a big family. You can view all the
technologies it contains from Projects on the official website.
- What Spring can do: It is used to develop web, microservices, and distributed systems. These three pieces alone account for
-
Spring has developed to this day and has formed a development ecosystem. Spring provides several projects, each of which is used to complete
specific functions. -
Spring has formed a complete ecosystem, which means that we can completely use Spring technology to complete the
construction, design and development of the entire project- Spring has several projects, you can choose according to your needs, combine these projects, and create a name called the whole family
bucket, as shown in the following figure - Spring has several projects, you can choose according to your needs, combine these projects, and create a name called the whole family
bucket, as shown in the following figure
Description:
What do the icons in the figure mean, you can enter https://spring. Check out the io/projects website for comparison.
Not all of these technologies need to be learned, additionally focus on Spring Framework, SpringBoot and SpringCloud:
- Spring has several projects, you can choose according to your needs, combine these projects, and create a name called the whole family
-
Spring Framework: The Spring Framework is the earliest and most core technology in Spring and the
foundation of all other technologies. -
SpringBoot: Spring is to simplify development, and SpringBoot is to help Spring develop faster on the basis of simplification -
SpringCloud: This is used for the development of distributed microservice architecture.
-
In addition to the above three technologies, there are many other technologies that are also popular, such as
SpringData, SpringSecurity, etc., which can be applied in our projects. The Spring we are learning today
actually refers to the Spring Framework
1.2, understand the development history of Spring
Next, let's introduce how the Spring Framework technology came about? The
history of Spring development
- IBM (IT company - International Business Machines Corporation) proposed the EJB idea in 1997, and most of the early JAVAEE development was based on this idea
- Expert One-on-One J2EE Design and Development by Rod Johnson (an expert in Java and J2EE development), published in 2002, describes how to use EJBs in development.
- Rod Johnson's Expert One-on-One J2EE Development without EJB published in 2004 proposed a more efficient implementation scheme than the EJB idea, and implemented the scheme in the same year. This implementation is
Spring1.0. - Over time, the version is constantly updated and maintained, and the latest one is Spring5
This section introduces the development history of the Spring family and Spring. What you need to master are:
- The Spring learned today is actually the Spring Framework in the Spring family
- Spring Framework is the underlying foundation of other frameworks in the Spring family. Learning Spring well can lay a solid foundation for the learning of other Spring frameworks.
02 Spring system architecture
Earlier we said that spring refers to the Spring Framework, so what does it contain and how do we learn this\framework?
For these problems, we will explain from the system architecture diagram and course learning route:
- Spring Framework is the most basic project in the Spring ecosystem and the foundation of other projects.
- The development of Spring Framework has also undergone many version changes, and each version has corresponding adjustments
- Version 5 of Spring Framework currently does not have the latest architecture diagram, and the latest is version 4, so the next main research
is the architecture diagram of 4
(1) Core layer - Core Container: The core container, this module is the core module of Spring, and everything else needs to depend on this module
(2) AOP layer
- AOP: Aspect-Oriented Programming, which relies on core-layer containers to
Without changing the original code
enhance it - Aspects: AOP is the idea, Aspects is the concrete realization of AOP idea
(3) Data layer - Data Access: Data access, there are specific implementation technologies for data access in the Spring family bucket
- Data Integration: Data integration, Spring supports the integration of other data layer solutions, such as Mybatis
- Transactions: transaction, transaction management in Spring is a specific implementation of Spring AOP, and it is also the key content of later learning
(4) Web layer - The content of this layer will be specifically learned in the SpringMVC framework
(5) Test layer - Spring mainly integrates Junit to complete unit testing and integration testing
03 Course study route
04 Spring core concepts
- In this part of the core concepts of Spring, IOC/DI, IOC container and Bean are mainly included, so the question is, what are these?
4.1 Problems in the current project
To answer this question, we need to first analyze the problems encountered in the writing process of our code:
(1) The business layer needs to call the method of the data layer, and the object of the new data layer in the business layer is required
(2) If the data If the implementation class of the layer changes, the code of the business layer also needs to be changed. After the change, it needs to be compiled,
packaged and redeployed
.
In response to this problem, how to solve it?
We thought, if we can remove the content in the box, wouldn't we be able to reduce the dependency, but it will introduce new problems,
can the program run after removing it? The
answer is definitely no , because bookDao is not assigned a value of Null, a null pointer exception will occur when forced to run.
So the problem now is that the business layer doesn't want the new object, and it needs this object when running. What should I do?
In response to this problem, Spring has proposed a solution:
when using objects, do not actively use new in the program to generate objects , converted to byexternal
The realization of providing objects is a core concept of Spring
4.2 IOC, IOC container, Bean, DI
-
IOC (Inversion of Control) Inversion of Control
(1) What is Inversion of Control?-
When using an object, the object generated by active new is converted to the object provided by the outside. In this process, the control of the object creation is transferred from the program to the outside. This idea is called inversion of control.
- The business layer uses the class object of the data layer, which used to be its own new
- Now that I am no longer new, I leave it to others [external] to create objects
- Others [external] invert control of the creation rights of data layer objects
- This idea is inversion of control
- What is someone else's [external] designation?
(2) What is the relationship between Spring and IOC?
- Spring technology implements the idea of IOC
- Spring provides a container, called the IOC container, to act as an "external" in the idea of IOC
- Others [external] in IOC thinking refer to Spring's IOC container
-
05, entry case
After introducing the core concepts of Spring, the next question we have to think about is how Spring implements IOC and DI. Next, we will demonstrate the specific implementation process through some simple introductory cases:
5.1 Introduction to IOC
For introductory cases, we have to analyze the ideas first and then implement the code.
5.1.1 Analysis of introductory case ideas
(1) Spring uses the container to manage bean objects, so what?
- Mainly manage the class objects used in the project, such as (Service and Dao)
(2) How to inform the IOC container of the managed object?
- Use configuration files
(3) The managed object is handed over to the IOC container. If you want to get the object from the container, you must first think about how to get the IOC container?
- Spring framework provides corresponding interfaces
(4) After the IOC container is obtained, how to obtain the bean from the container?
- Call the methods in the corresponding interface provided by the Spring framework
(5) Which coordinates are imported using Spring?
- If you use other people's things, you need to add the corresponding dependency to the
original method in pom.xml
public class BookDaoImpl implements BookDao {
public void save ( ) {
System . out . println ( "book dao save ..." ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
public class BookServiceImpl implements BookService {
//5. Delete the dao object created using new in the business layer
private BookDao bookDao = new BookDaoImpl ( ) ;
public void save ( ) {
System . out . println ( "book service save ..." ) ;
bookDao . save ( ) ;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class App {
public static void main ( String [ ] args ) {
BookService bookService = new BookServiceImpl ( ) ;
bookService . save ( ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
For the convenience of using spring
, it is written as follows. Four are written in one file, but they are actually in four files.
Step 5: Complete the bean configuration in the configuration file
<!--1. Import spring's coordinates spring-context, the corresponding version is 5.2.10.RELEASE-->
<!--2. Configuration bean-->
<!--bean tag indicates configuration bean
The id attribute indicates the name of the bean (the name can be written casually)
The class attribute indicates that the type is defined for the bean -->
< bean id = " bookDao " class = " com.itheima.dao.impl.BookDaoImpl " />
< bean id = " bookService " class = " com.itheima.service.impl.BookServiceImpl " />
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Note: When the bean is defined, the id attribute cannot be repeated in the same context (configuration file).
The Spring IOC entry case has been completed, but the new operation of the BookDaoImpl object still exists in the BookServiceImpl class, and the coupling between them is still relatively high. , how to solve this, you need to use the following DI: dependency injection.
5.2 DI entry case
For the entry case of DI, we still analyze the ideas first and then implement the code. The
idea of entry case analysis
** Entry case code implementation**
06, IOC related content
Through the previous two cases, we have learned how beans define configuration, how DI defines configuration, and how container objects are obtained. Next, we will explain these three parts in detail, and study these three parts in depth. The content, first of all, the basic configuration of the bean
.
6.1 bean basic configuration
For the bean configuration, the basic bean configuration, bean alias configuration, bean scope configuration (focus
), these three parts
:
6.2 Bean basic configuration (id and class)
6.3 bean's name attribute
6.4 bean scope configuration
Verify that the object in the IOC container is a singleton
** Configure the bean as a non-singleton**
scope use follow-up thinking
6.5 Summary of bean basic configuration
6.6 bean instantiation (there are three ways)
1 Construction method (commonly used)
Environmental preparation
constructor instantiation
2 Static factory (understand)
3 Instance factory (understanding) and FactoryBean (practical)-p11
6.7 Bean life cycle
07 The way of dependency injection
7.1 Setter injection
7.2 Constructor Injection
7.3 Automatic assembly
day02-(22:00)
Annotation development
Spring integrates mybatis
Spring integrates JUnit
There is a big difference between integrating Junit and integrating Druid and MyBatis. Why? Junit is a tool for unit testing. It
is not the main body of our program, and it will not participate in the running of the final program. In terms of function, it is different from the previous ones. It is not a
function, but is regarded as an auxiliary tool. That's it.
Environmental preparation
In this environment, you can directly use the environment integrated with Spring and Mybatis. Of course, you can also create a new one, because the
content is exactly the same, so we can directly look at the project structure.
Integrate Junit steps
Step 1: Introduce dependency
pom.xml
< dependency >
< groupId > junit </ groupId >
< artifactId > junit </ artifactId >
< version > 4.12 </ version >
< scope > test </ scope >
</ dependency >
< dependency >
< groupId > org.springframework </ groupId >
< artifactId > spring-test </ artifactId >
< version > 5.2.10.RELEASE </ version >
</ dependency >
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
Step 2: Write a test class
Create an AccountServiceTest under test\java, the name is arbitrary
package com . itheima . service ;
import com.itheima.config.SpringConfig ; import org.junit.Test ; import org.junit.runner.RunWith ;
import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.test.context.ContextConfiguration ; _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
import org . springframework . test . context . junit4 . SpringJUnit4ClassRunner ;
// The following two lines of code will not change in this life.
// Set the class runner
@RunWith ( SpringJUnit4ClassRunner . class )
// Set the configuration class corresponding to the Spring environment
@ContextConfiguration ( classes = SpringConfig . class )
public class AccountServiceTest {
//Support autowired injection bean
@Autowired
private AccountService accountService ;
@Test
public void testFindById ( ) {
System . out . println ( accountService . findById ( 1 ) ) ;
}
@Test
public void testFindAll ( ) {
System . out . println ( accountService . findAll ( ) ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
day03
Aop
1. Introduction to AOP
When we introduced Spring earlier, we said that Spring has two core concepts, one is IOC/DI and the other is AOP.
The IOC/DI has been systematically studied before, and another core content of it is to be learned, which is AOP.
For AOP, we mentioned a sentence earlier:AOP is to enhance the original code without changing it.
For the following content, we mainly focus on this sentence to study, mainly learn two aspects of AOP core concepts, AOP role:
1.1 What is AOP?
- AOP (Aspect Oriented Programming) Aspect Oriented Programming, a programming paradigm that guides developers on how to organize the program
structure- OOP (Object Oriented Programming) Object-oriented programming
We all know that OOP is a programming idea, so AOP is also a programming idea. The main content of programming ideas is to guide programmers
how to write programs, so they are two different programming paradigms .
- OOP (Object Oriented Programming) Object-oriented programming
1.2 The role of AOP
- Function: To enhance the function without disturbing the original design, we can realize such a function, namely the proxy
mode
, if we have the technology.
1.3 AOP core concepts
In order to better understand the related concepts of AOP, we have prepared an environment. We can ignore the content of the entire environment for the time being. The
main class is: BookDaoImpl
package com . itheima . dao . impl ;
import com . itheima . dao . BookDao ;
import org . springframework . beans . factory . annotation . Value ;
import org . springframework . stereotype . Repository ;
@Repository
public class BookDaoImpl implements BookDao {
public void save ( ) {
//Record the current execution of the program (start time)
Long startTime = System . currentTimeMillis ( ) ;
// 10,000 times of business execution
for ( int i = 0 ; i < 10000 ; i ++ ) {
System . out . println ( "book dao save ..." ) ;
}
//Record the current execution time (end time) of the program
Long endTime = System . currentTimeMillis () ;
//Calculate the time difference
Long totalTime = endTime - startTime ;
//Output information
System . out . println ( "Execution time of 10,000 times: " + totalTime + "ms" ) ;
}
public void update ( ) {
System . out . println ( "book dao update ..." ) ;
}
public void delete ( ) {
System . out . println ( "book dao delete ..." ) ;
}
public void select ( ) {
System . out . println ( "book dao select ..." ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
The content of the code is believed to be understood by everyone. For the save method, there is a calculation of the time consumed by 10,000 executions.
When the bookDao object is obtained from the container in the App class, and the save, delete, update and select methods are executed respectively, there will
be the following print results:
At this time, we should have some questions?
- For calculating the time consumed by 10,000 executions, only the save method has it. Why do the delete and update methods also have it?
- There are delete and update methods, so why is there no select method?
In this case, Spring's AOP is actually used. On the premise of not disturbing (changing) the original design (code), you can add functions
to whomever you want. Add to. This is also the concept of Spring: - Non-intrusive / non-intrusive Having
said that, how does Spring achieve this?
2. AOP entry case
2.1 Demand Analysis
2.2 Analysis of ideas
2.3 Environmental preparation
- Create a Maven project
- pom.xml add Spring dependencies
< dependency >
< groupId > org.springframework </ groupId >
< artifactId > spring-context </ artifactId >
< version > 5.2.10.RELEASE </ version >
</ dependency >
- 1
- 2
- 3
- 4
- 5
- Add BookDao and BookDaoImpl classes
package com . itheima . dao . impl ;
import com . itheima . dao . BookDao ;
import org . springframework . beans . factory . annotation . Value ;
import org . springframework . stereotype . Repository ;
@Repository
public class BookDaoImpl implements BookDao {
public void save ( ) {
System . out . println ( System . currentTimeMillis ( ) ) ;
System . out . println ( "book dao save ..." ) ;
}
public void update ( ) {
System . out . println ( "book dao update ..." ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- Create Spring configuration class
package com . itheima . config ;
import org.springframework.context.annotation.ComponentScan ; import org.springframework.context.annotation.Configuration ; import org.springframework.context.annotation.EnableAspectJAutoProxy ; _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
//This is to tell spring to load my
@Configuration
@ComponentScan ( "com.itheima" )
public class SpringConfig {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- Write the App running class
package com.itheima ; _ _
import com.itheima.config.SpringConfig ; import com.itheima.dao.BookDao ; import org.springframework.context.ApplicationContext ;
import org.springframework.context.annotation.AnnotationConfigApplicationContext ; _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
public class App {
public static void main ( String [ ] args ) {
ApplicationContext ctx = new AnnotationConfigApplicationContext ( SpringConfig . class ) ;
BookDao bookDao = ctx . getBean ( BookDao . class ) ;
bookDao . update ( ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
The final created project structure is as follows:
2.4 AOP implementation steps
pom.xml
< dependency >
< groupId > org.aspectj </ groupId >
< artifactId > aspectjweaver </ artifactId >
< version > 1.9.4 </ version >
</ dependency >
- 1
- 2
- 3
- 4
- 5
Step 2: Define the interface and implementation class
When the environment is ready, BookDaoImpl is ready and does not need to be modified
Step 3: Define notification class and notification
Notification is a method formed by extracting common functions. Common functions refer to the printing of the current system time.
public class MyAdvice {
public void method ( ) {
System . out . println ( System . currentTimeMillis ( ) ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
The class name and method name are not required and can be arbitrary.
Step 4: Define the entry point
BookDaoImpl There are two methods, save and update, we want to enhance the update method, how to define it?
public class MyAdvice {
@Pointcut ( "execution(void com.itheima.dao.BookDao.update())" )
private void pt ( ) { }
@Before ( "pt()" )
public void method ( ) {
System . out . println ( System . currentTimeMillis ( ) ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Step 5: Make Aspects
Aspects are used to describe the relationship between notifications and pointcuts. How to bind the relationship?
public class MyAdvice {
@Pointcut ( "execution(void com.itheima.dao.BookDao.update())" )
private void pt ( ) { }
@Before ( "pt()" )
public void method ( ) {
System . out . println ( System . currentTimeMillis ( ) ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Step 6: Assign the notification class to the container and identify it as an aspect class
@Component
// Tell spring that I am aop
@Aspect
public class MyAdvice {
@Pointcut ( "execution(void com.itheima.dao.BookDao.update())" )
private void pt ( ) { }
@Before ( "pt()" )
public void method ( ) {
System . out . println ( System . currentTimeMillis ( ) ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Step 7: Enable the annotation format AOP function
//This is to tell spring to load me
@Configuration
@ComponentScan ( "com.itheima" )
//Enable annotation to develop AOP function This corresponds to the previous @Aspect
@EnableAspectJAutoProxy
public class SpringConfig {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Step 8: Run the Program
public class App {
public static void main ( String [ ] args ) {
ApplicationContext ctx = new AnnotationConfigApplicationContext ( SpringConfig . class ) ;
BookDao bookDao = ctx . getBean ( BookDao . class ) ;
bookDao . update ( ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Seeing that the system timestamp is printed before the update method is executed, it shows that the original method has been enhanced and the AOP programming is successful.
3. AOP workflow
4. AOP configuration management
4.1 AOP pointcut expressions
In the process of learning, slowly become proficient, don't memorize by rote
4.2 AOP Notification Types (p35)
The directory structure is as follows
4.2.1 Type introduction
4.2.2 Environmental Preparation
< dependencies >
< dependency >
< groupId > org.springframework </ groupId >
< artifactId > spring-core </ artifactId >
< version > 5.2.10.RELEASE </ version >
</ dependency >
< dependency >
< groupId > org. aspectj </ groupId >
< artifactId > aspectjweaver </ artifactId >
<version > 1.9.4 </ version >
</ dependency >
</ dependencies >
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- Add BookDao and BookDaoImpl classes
public interface BookDao {
public void update ( ) ;
public int select ( ) ;
}
@Repository
public class BookDaoImpl implements BookDao {
public void update ( ) {
System . out . println ( "book dao update ..." ) ;
}
public int select ( ) {
System . out . println ( "book dao select is running ..." ) ;
return 100 ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- Create a configuration class for Srin
@Configuration
@ComponentScan ( "com.itheima" )
@EnableAspectJAutoProxy
public class SpringConfig {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- Create a notification class
@Component
@Aspect
public class MyAdvice {
@Pointcut ("execution(void com.itheima.dao.BookDao.update())" )
private void pt ( ) {
}
@Before ( "pt()" )
//This can also be written as @Before("MyAdvice.pt()"),
public void before ( ) is not recommended {
System . out . println ( "before advice ..." ) ;
}
@After ( "pt()" )
public void after ( ) {
System . out . println ( "after advice ..." ) ;
}
public void around ( ) {
System . out . println ( "around before advice ..." ) ;
System . out . println ( "around after advice ..." ) ;
}
public void afterReturning ( ) {
System . out . println ( "afterReturning advice ..." ) ;
}
public void afterThrowing ( ) {
System . out . println ( "afterThrowing advice ..." ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- Write the App running class
public class App {
public static void main ( String [ ] args ) {
ApplicationContext ctx = new AnnotationConfigApplicationContext ( SpringConfig . class ) ;
BookDao bookDao = ctx . getBean ( BookDao . class ) ;
bookDao . update ( ) ;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Surround notifications (most important)
@Pointcut ( "execution(void com.itheima.dao.BookDao.update())" )
private void pt1 ( ) { }
@Around ( "pt1()" )
public void around ( ) {
System . out . println ( "around before advice ..." ) ;
System . out . println ( "around after advice ..." ) ;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
In the running result, the content of the notification is printed, but the content of the original method is not executed.
Because the surround advice needs to be enhanced before and after the original method, the surround advice must be able to call the original operation.
How to implement it?
@Around ( "pt1()" )
public void around ( ProceedingJoinPoint pjp ) throws Throwable {
System . out . println ( "around before advice ..." ) ;
//represents a call to the original operation
pjp . proceed ( ) ;
System . out . println ( "around after advice ..." ) ;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Matters needing attention
(1) The original method has return value processing
Modify MyAdvice, add surround notification to the select method in BookDao,
4.3 Business Layer Interface Execution Efficiency (p36)
Like is the way the way the way the way I don't understand the way I don't understand the way
4.4 AOP notification to acquire data (p37)
4.5 Baidu network disk password data compatibility processing (p38)
5. AOP summary
6. AOP transaction management (around p32)
6.1 Introduction to Spring Transactions
6.1.1 Introduction to related concepts
In order to manage transactions, Spring provides a platform transaction managerPlatformTransactionManager
References
Related: Spring Basics
- 01 Introduction to Spring
- 02 Spring system architecture
- 03 Course study route
- 04 Spring core concepts
- 05, entry case
- 06, IOC related content
- 07 The way of dependency injection
- day02-(22:00)
- day03
- Aop