ishowcode.eth

ishowcode.eth

区块链小白

Introduction to Spring and Detailed Explanation of IOC

Introduction to Spring and Configuration#

Learning Objectives#

  • [Application] Able to independently complete a quick start with Spring IOC
  • [Application] Able to master the configuration of Spring's bean tags
  • [Application] Able to independently complete object property injection for beans
  • [Application] Able to independently complete ordinary property injection for beans
  • [Understanding] Able to independently complete collection property injection for beans

1. Overview of Spring#

1.1 What is Spring#

Insert image description here

Spring is a layered lightweight open-source framework for Java SE/EE applications, with IoC (Inversion Of Control) and AOP (Aspect Oriented Programming) at its core. It provides numerous enterprise-level application technologies such as the presentation layer Spring MVC, the persistence layer Spring JDBCTemplate, and business layer transaction management, and can integrate many well-known third-party frameworks and libraries from the open-source world, gradually becoming the most widely used open-source framework for Java EE enterprise applications.

1.2 Development History of Spring#

In 1997, IBM proposed the concept of EJB.
In 1998, SUN established the development standard specification EJB 1.0.
In 1999, EJB 1.1 was released.
In 2001, EJB 2.0 was released.
In 2003, EJB 2.1 was released.
In 2006, EJB 3.0 was released.
Rod Johnson (Father of Spring)
Insert image description here

"Expert One-to-One J2EE Design and Development" (2002) elaborated on the advantages and solutions of using EJB for J2EE development and design.
"Expert One-to-One J2EE Development without EJB" (2004) elaborated on the solutions for J2EE development without using EJB (Spring prototype).
In July 2021, the latest version of Spring, Spring 5.3.9, was officially released.

1.3 Advantages of Spring (Understanding)#

1. Convenient Decoupling, Simplifying Development#

Spring is like a large factory (IoC container) that can manage the creation of all objects and the maintenance of their dependencies, greatly reducing the coupling between components.

2. Support for AOP Programming#

With Spring's AOP capabilities, aspect-oriented programming is easily facilitated, allowing many functionalities that are difficult to achieve with traditional OOP to be easily implemented through AOP, such as permission interception and runtime monitoring.

3. Support for Declarative Transactions#

It liberates us from monotonous and tedious transaction management code, allowing flexible transaction management through declarative means, improving development efficiency and quality.

4. Convenient Testing of Programs#

Spring supports Junit4, allowing easy testing of Spring programs through annotations, making testing no longer an expensive operation but something that can be done easily.

5. Convenient Integration of Various Excellent Frameworks#

Spring does not exclude various excellent open-source frameworks and provides direct support for many excellent frameworks (such as Struts, Hibernate, MyBatis, Quartz, etc.).

6. Reducing the Difficulty of Using JavaEE APIs#

Spring encapsulates some very difficult-to-use APIs in JavaEE development (JDBC, JavaMail, remote calls, etc.), significantly reducing the difficulty of using these APIs.

7. Java Source Code as a Classic Learning Example#

The design of Spring's source code is exquisite, with a clear structure and unique craftsmanship, reflecting the master's flexible application of Java design patterns and profound knowledge of Java technology. Its source code is unintentionally the best practice example of Java technology.

1.4 Spring's Architecture (Understanding)#

Insert image description here

2. Quick Start with Spring IoC#

2.1 Concept and Role of IoC#

IoC: Inversion Of Control means that the application itself is not responsible for the creation and maintenance of dependent objects; this responsibility is handled by an external container. Thus, control is transferred from the application to the external container, and this transfer of control is what is referred to as inversion.

In simple terms: delegate the creation, initialization, and destruction of objects to the Spring container. The Spring container controls the lifecycle of the objects.

Clarifying the role of IoC: reducing the coupling of computer programs (removing dependencies in our code).
Originally: we used the new method to obtain objects actively.
Now: we obtain objects from the Spring container passively, allowing Spring to find or create the objects for us.

2.2 Steps for Spring IoC Program Development#

  1. Import the basic package coordinates for Spring development.
  2. Write the Dao interface and implementation class.
  3. Create the Spring core configuration file.
  4. Configure UserDaoImpl in the Spring configuration file.
  5. Use Spring's API to obtain Bean instances.

2.3 Import Basic Package Coordinates for Spring Development#

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

2.4 Write Dao Interface and Implementation Class#

package com.summer.dao;
public interface UserDao {
public void save();
} 

package com.summer.dao.impl;
import com.summer.dao.UserDao;
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("User added~~~~~");
}
}

2.5 Create Spring Core Configuration File#

Create the applicationContext.xml configuration file in the classpath (resources).

<?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">
</beans>

2.6 Configure UserDaoImpl in Spring Configuration File#

<?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">
<!-- Delegate the creation of the object to the Spring container -->
<bean id="userDao" class="com.bailiban.dao.impl.UserDaoImpl"></bean>
</beans>

2.7 Use Spring's API to Obtain Bean Instances#

public class TestIoC {
public static void main(String[] args) {
// Create Spring container instance
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// Get bean from the container based on unique identifier id
UserDao userDao = (UserDao) context.getBean("userDao");
userDao.save();
}
}

Look for the configuration file in the classpath to instantiate the container.
Spring Quick Start Code Reinforcement Exercise
Practice instantiating objects through Spring IoC's XML configuration method:

  1. Import coordinates
  2. Create Bean
  3. Create configuration file applicationContext.xml
  4. Configure in the configuration file
  5. Create ApplicationContext object getBean

3. Introduction to Bean Dependency Injection#

  1. Write Dao and Service interfaces and implementation classes.
public interface UserDao {
public void save();
} 
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("User added~~~~~");
}
} 
public interface UserService {
public void save();
} 
public class UserServiceImpl implements UserService {
public void save() {
//TODO
}
}
  1. Delegate the creation rights of UserDaoImpl and UserServiceImpl to Spring.
<!-- Spring IoC delegates the creation rights of the object to Spring -->
<bean id="userDao" class="com.bailiban.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.bailiban.service.impl.UserServiceImpl"></bean>

UserService internally calls the save() method of UserDao.

public class UserServiceImpl implements UserService {
public void save() {
// Create Spring container instance
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// Get dao object based on id
UserDao userDao = (UserDao) context.getBean("userDao");
// Call method
userDao.save();
}
}
  1. Obtain UserService from the Spring container for operations.
public class TestDI {
// Test DI quick start
@Test
public void test1() {
// Create Spring container instance
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// Get dao object based on id
UserService userService = (UserService) context.getBean("userService");
// Call method
userService.save();
}
}

3.1 Analysis of Bean Dependency Injection#

Currently, both UserService and UserDao instances exist in the Spring container. The current approach is to obtain UserService and UserDao instances from outside the container and then combine them in the program.
Insert image description here

Since both UserService and UserDao are in the Spring container, and the program ultimately uses UserService, we can set UserDao inside UserService within the Spring container.

Insert image description here

3.2 Concept of Bean Dependency Injection#

DI: Dependency Injection requires an IoC environment. During the object creation process, Spring injects the properties that the object depends on into the object.

When writing programs, by controlling inversion, the creation of objects is delegated to Spring, but it is impossible for the code to have no dependencies.

IoC decoupling only reduces their dependencies but does not eliminate them. For example, the business layer will still call methods from the persistence layer.
After using Spring, this dependency relationship between the business layer and the persistence layer is maintained by Spring.
In simple terms, it means waiting for the framework to pass the persistence layer object into the business layer without us having to retrieve it ourselves.

3.3 Ways of Bean Dependency Injection#

How to inject UserDao into UserService?

3.3.2 Set Method#

Add a setUserDao method in UserServiceImpl.

public class UserServiceImpl implements UserService {
// Define dao member variable
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} 
public void save() {
// // Create Spring container instance
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// // Get dao object based on id
// UserDao userDao = (UserDao) context.getBean("userDao");
// // Call method
userDao.save();
}
}

Configure the Spring container to call the set method for injection.

<bean id="userDao" class="com.bailiban.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.bailiban.service.impl.UserServiceImpl">
<!-- Use set method for injection
name: remove "set" and lowercase the first letter -->
<property name="userDao" ref="userDao"></property>
</bean>

Set method: P namespace injection
P namespace injection is essentially also set method injection, but it is more convenient than the above set method injection, mainly reflected in the configuration file, as follows:
First, introduce the P namespace:

xmlns:p="http://www.springframework.org/schema/p"

Then, modify the injection method.

<bean id="userService" class="com.bailiban.service.impl.UserServiceImpl" p:userDao-ref="userDao">

3.4 Data Types for Bean Dependency Injection#

The above operations are all about injecting reference Beans. In addition to object references, ordinary data types can also be injected into the container.
Two data types for injection:

  1. Ordinary data types
  2. Reference data types
    Among them, reference data types will not be elaborated here; the previous operations have all been about injecting references to the UserDao object. Below, we will demonstrate the injection of ordinary data types using the set method.
    Data Types for Bean Dependency Injection
    (1) Injection of ordinary data types
    Practice:
public class UserDaoImpl implements UserDao {
// Injection of ordinary data types
private String name;
private int age;
public void setName(String name) {
this.name = name;
} 
public void setAge(int age) {
this.age = age;
} 
public void save() {
System.out.println(name+"‐‐‐"+age);
System.out.println("User added~~~~~");
}
} 
<bean id="userDao" class="com.bailiban.dao.impl.UserDaoImpl">
<!-- Injection of ordinary data -->
<property name="name" value="Wangcai"></property>
<property name="age" value="18"></property>
</bean>
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.