Learn an in-depth understanding of IOC and AOP
“This is the third day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.
About the author
- The authors introduce
🍓 blog home page: author’s home page 🍓 Introduction: JAVA quality creator 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors
1. Overview of Spring
This article provides Spring related learning experience and experience. A comprehensive introduction to all the functions of Spring, as well as the basic concepts involved in Spring (such as Dependency Injection).
If you are new to Spring, you may need to start your Spring framework journey by creating a Spring Boot application. Spring Boot provides a fast (and autonomous) way to create a Spring-based production environment. It’s based on the Spring framework, supports convention over configuration, and is designed to get you up and running as quickly as possible.
You can use start.spring. IO to generate a base project or follow any of the instructions in the Beginner’s Guide to build the project. To make it easier for you to understand, these guides are task-oriented, and most of them are based on Spring Boot. They also cover a number of Spring prototyping projects that you can consider using when you need to solve specific problems.
2. Introduction to Spring
- It’s Spring time for the software development industry
- In 2002, Rod Jahnson first introduced the Interface21 framework, a prototype of the Spring framework. On March 24, 2004, the Spring framework, based on the Interface21 framework, was redesigned and released as version 1.0.
- Rod Johnson (founder of the Spring Framework), he has a PhD from the University of Sydney, but his major is not computer science, it’s musicology. It seems that big guy or big guy, no matter in which aspects are very strong.
- Spring philosophy: Make existing technologies more practical. It is a hodgepodge in itself, integrating existing framework technologies.
The Spring framework is a Java platform that provides comprehensive infrastructure support for developing Java applications.
Spring takes care of the infrastructure, so you can focus on application development.
Spring lets you build applications from “Plain Old Java Objects” (POJOs) and implement enterprise application services through non-invasive POJOs. This feature applies to the Java SE programming model, and is fully or partially adapted to the Java EE model.
How to get the most out of Spring as a developer:
- Write a Java method to execute a database transaction without having to deal with the APIs for the specific transaction.
- Write a native Java method to make remote calls without having to deal with the remote call APIs.
- Write a native Java method to implement administrative operations without having to deal with JMX APIs.
- Write a native Java method to implement message handling without having to deal with the JMS APIs.
Liverpoolfc.tv: spring. IO /
IO /libs-releas…
Making: github.com/spring-proj…
advantages
- Spring is an open source, free framework that acts as a container for storage.
- Spring is a lightweight framework that is non-intrusive. (Designers “take” client functionality into the framework)
- Inversion of control IOC, faceted AOP. This is the point ~~~~
- Support for things, support for frameworks.
In a nutshell: Spring is a lightweight inversion of Control (IoC) and AOP oriented container (framework).
3, composition
The Spring framework is a layered architecture consisting of seven well-defined modules. Spring modules are built on top of the core container, which defines how beans are created, configured, and managed.
Each module (or component) that makes up the Spring framework can exist on its own or be implemented in conjunction with one or more other modules. That is to say, aggregate when in use, separate when not in use, and achieve the effect of decoupling.
The functions of each module are as follows:
Spring Core: The Core container provides the basic functionality of the Spring framework. The main component of the core container is the BeanFactory, which is an implementation of the factory pattern. The BeanFactory uses the Inversion of Control (IOC) pattern to specification the configuration and dependencies of the application. Separate from the actual application code.
Spring Context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services, such as JNDI, EJB, E-mail, internationalization, validation, and scheduling capabilities.
Spring AOP: The Spring AOP module integrates section-oriented programming functionality directly into the Spring framework through the configuration management feature. So, you can easily have the Spring framework manage any OBJECT that supports AOP. The Spring AOP module provides transaction management services for objects in Spring-based applications. Using Spring AOP, you can integrate declarative transaction management into your application without relying on components.
Spring DAO: The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. Exception hierarchies simplify error handling and greatly reduce the amount of unusual code you need to write (such as opening and closing connections). Spring DAO’s JDBC-oriented exceptions follow a common DAO exception hierarchy.
Spring ORM: The Spring framework inserts several ORM frameworks to provide ORM’s object-relational tools, including JDO, Hibernate, and iBatis SQL Map. All follow Spring’s common transaction and DAO exception hierarchies.
Spring Web: The Web context module builds on the application context module and provides the context for Web-based applications. So, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies handling multi-part requests and binding request parameters to domain objects.
Spring WEB MVC: The MVC framework is a full-featured MVC implementation for building WEB applications. With the policy interface, the MVC framework becomes highly configurable, and MVC accommodates a number of view technologies, including JSP, Velocity, Tiles, iText, and POI.
4. IOC foundation
Create a new empty Maven project
4.1 Analysis and Implementation
First we should import the dependencies
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Spring5study</artifactId>
<groupId>org.example</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-ioc1</artifactId>
<dependencies>
<! -- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9. RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3 requires. RELEASE</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Copy the code
Let’s write a piece of code in our original way.
1. Write a UserDao interface
package com.spring.dao;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.dao
* @ClassName: UserDao
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:06
* @Version: 1.0 * /
public interface UserDao {
public void getuser(a);
}
Copy the code
2. Write the Dao implementation class again
package com.spring.dao;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.dao
* @ClassName: UserDaoImpl
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:07
* @Version: 1.0 * /
public class UserDaoImpl implements UserDao{
@Override
public void getuser(a) {
System.out.println("Get the user's information"); }}Copy the code
3. Write to the UserService interface
package com.spring.service;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.service
* @ClassName: UserService
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:07
* @Version: 1.0 * /
public interface UserService {
public void getuser(a);
}
Copy the code
4. Finally write the Service implementation class
package com.spring.service;
import com.spring.dao.UserDao;
import com.spring.dao.UserDaoImpl;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.service
* @ClassName: UserServiceImpl
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:08
* @Version: 1.0 * /
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImpl();
@Override
public void getuser(a) { userDao.getuser(); }}Copy the code
5. Test
import com.spring.service.UserService;
import com.spring.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
/ * * *@ProjectName: Spring5study
* @Package: PACKAGE_NAME
* @ClassName: MyTest
* @Author: Shengrui Zhang *@Date: 2022/1/20 * have closed@Version: 1.0 * /
public class MyTest {
@Test
void test1(a){
UserService userService = newUserServiceImpl(); userService.getuser(); }}Copy the code
This is the way we used to do it, and this is how we started. Let’s change it now.
Now add a class UserDaoMysqlImpl to the Userdao implementation class
package com.spring.dao;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.dao
* @ClassName: UserDaoMysqlImpl
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:17
* @Version: 1.0 * /
public class UserDaoMysqlImpl implements UserDao{
@Override
public void getuser(a) {
System.out.println(Get information about this user's connection to Mysql); }}Copy the code
Next we need to use MySql, we need to modify the corresponding implementation in the service implementation class
package com.spring.service;
import com.spring.dao.UserDao;
import com.spring.dao.UserDaoImpl;
import com.spring.dao.UserDaoMysqlImpl;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.service
* @ClassName: UserServiceImpl
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:08
* @Version: 1.0 * /
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoMysqlImpl();
@Override
public void getuser(a) { userDao.getuser(); }}Copy the code
Run the test file to find output information about Mysql
Suppose we add another implementation class for the Userdao, UserDaoOracleImpl
package com.spring.dao;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.dao
* @ClassName: UserDaoOracleImpl
* @Author: Shengrui Zhang *@Date: 2022/1/20 time *@Version: 1.0 * /
public class UserDaoOracleImpl implements UserDao{
@Override
public void getuser(a) {
System.out.println("Get Oracle connection information for this user"); }}Copy the code
Then we need to use Oracle to obtain the user’s information, and we need to modify the corresponding implementation in the Service implementation class. Let’s say we have a huge need for this, and it’s not going to work, it’s not going to work, it’s not going to work, it’s not going to work, it’s going to change a lot of code every time. The coupling of this design is so high that it causes the program to crash.
So how do we solve it?
We can, instead of implementing it where we need to use it, we can set up an interface, use set, and we can modify it in the code.
package com.spring.service;
import com.spring.dao.UserDao;
import com.spring.dao.UserDaoImpl;
import com.spring.dao.UserDaoMysqlImpl;
/ * * *@ProjectName: Spring5study
* @Package: com.spring.service
* @ClassName: UserServiceImpl
* @Author: Shengrui Zhang *@Date: 2022/1/20 17:08
* @Version: 1.0 * /
public class UserServiceImpl implements UserService{
// We find that the object is not instantiated
private UserDao userDao;
// Use set to do this
public UserDao getUserDao(a) {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getuser(a) { userDao.getuser(); }}Copy the code
Now go to our test class and test it
@Test
public void test2(a){
UserServiceImpl service = new UserServiceImpl();
service.setUserDao( new UserDaoMysqlImpl() );
service.getuser();
// Now we want to use Oracle to implement
service.setUserDao( new UserDaoOracleImpl() );
service.getuser();
}
Copy the code
Do you see the difference? A lot of people say it doesn’t make a difference. But when you look closely, they have changed radically, in many ways. If you think about it carefully, before everything was created by the program, now we control the creation of objects, giving the initiative to the caller (i.e. the user), the program does not care how to create, how to implement, it is only responsible for providing an interface.
This idea, in essence, solves the problem. We programmers no longer manage the creation of objects, but pay more attention to the implementation of business. Coupling is greatly reduced. This is the prototype of IOC!
Let’s draw a picture of what’s going on.
4.2 the IOC nature
Inversion of Control (IoC) is a design idea, DI(dependency injection) is a method to implement IoC, but some people think DI is just another word for IoC. In programs without IOC, we use object-oriented programming, in which the creation of objects and the dependencies between objects are completely hard-coded in the program, the creation of objects is controlled by the program itself, and the creation of objects is transferred to a third party after the inversion of control. In my opinion, the so-called inversion of control is: the way of obtaining dependent objects is reversed.
IOC is at the heart of the Spring framework and is implemented beautifully in a variety of ways, including XML configuration, annotations, and zero configuration in new versions of Spring.
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.
When configuring beans in XML mode, Bean definition information is separated from the implementation, while annotations can be used to combine the two. Bean definition information is directly defined in the form of annotations in the implementation class, thus achieving zero configuration.
Inversion of control is a way to produce or obtain a particular object through a description (XML or annotations) and through a third party. Inversion of control is implemented in Spring by the IoC container through Dependency Injection (DI).
After the language
The original intention of the director to write blog is very simple, I hope everyone in the process of learning less detours, learn more things, to their own help to leave your praise 👍 or pay attention to ➕ are the biggest support for me, your attention and praise to the director every day more power.
If you don’t understand one part of the article, you can reply to me in the comment section. Let’s discuss, learn and progress together!
Wechat (Z613500) or QQ (1016942589) for detailed communication.