IoC decoupling learning and practice of Spring

Overview of Spring

What is spring

Spring is a lightweight open source framework for layered Java SE/EE applications, IoC (Inverse Of Control) and AOP (aspect oriented programming: Aspect Oriented Programming) as the kernel, it provides many enterprise application technologies such as presentation layer spring MVC, persistence layer Spring JDBC and business layer transaction management. It can also integrate many famous third-party frameworks and class libraries in the world, and gradually become the most used Java EE enterprise application open source framework.

Two cores of spring

IoC (reverse of control): for example, for a class, if we want to call a method in the class (not a static method), we need to create an object of the class and use the object call method to implement it. However, for Spring, the process of creating an object is not implemented in the code, but entrusted to Spring for configuration and implementation;

AOP (Aspect Oriented Programming): extends program functions without directly modifying the original code.

Advantages of spring

  • 1. Facilitate decoupling and simplify development

Through the IoC container provided by Spring, the dependencies between objects can be controlled by Spring to avoid hard coding
Excessive program coupling. Users do not have to write code for the very low-level requirements such as singleton pattern class and attribute file parsing, and can focus more on the upper-level applications.

  • 2.AOP programming support

Through the AOP function of Spring, it is convenient for aspect oriented programming. Many functions that are not easy to implement with traditional OOP can be easily handled through AOP.

  • 3. Support for declarative transactions

It can free us from the monotonous and boring transaction management code, and flexibly manage transactions in a declarative way, so as to improve the development efficiency and quality.

  • 4. Facilitate program testing

Almost all testing work can be carried out in a container independent programming way. Testing is no longer an expensive operation, but a thing to do at will.

  • 5. It is convenient to integrate various excellent frameworks

Spring can reduce the difficulty of using various frameworks and provide direct support for various excellent frameworks (Struts, Hibernate, Hessian, Quartz, etc.).

  • 6. Reduce the difficulty of using Java EE API

Spring has a thin encapsulation layer for Java EE APIs (such as JDBC, JavaMail, remote call, etc.), which greatly reduces the difficulty of using these APIs.

Architecture of Spring 5


The spring framework is a layered architecture consisting of seven well-defined modules. Spring module is built on the core container, which defines the way to create, configure and manage bean s

The above figure is the module structure diagram of Spring 5. These components are integrated in Core Container, AOP (Aspect Oriented Programming), Instrument, data access / integration, Web, Messaging, Test and other modules.

Program coupling and decoupling

introduce

For the development of persistence layer (dao layer), the general practice for beginners is to create an interface first, and then create the implementation class corresponding to the interface.
The code is as follows:
1. First create a Userdao interface.

public interface UserDao {
	public void add();
}

2. Create an implementation class of the Userdao interface (UserDaoImpl.java).

public class UserDaoImpl implements UserDao {
    public void add() {
	    //.....
    }
}

3, call the dao layer in the service layer.

// Interface instance variable = new implementation class
UserDao dao = new UserDaoImpl();
dao.add();

We can find that the coupling between the service layer and dao layer is too high, that is, the interface and implementation classes are coupled (with dependencies). As long as the underlying implementation classes are switched, the source code needs to be modified. Obviously, this is not a good design. One of the seven principles of object-oriented design is to meet the opening and closing principle, that is, "open for extension and close for modification".

Factory mode decoupling

To solve this problem, you need to use the factory design pattern to decouple, first create a factory class, provide a method in the factory class, and return the object of the implementation class. Then the core code of the dao layer is called in the service layer. The code is as follows:
1. Create factory class

public class BeanFactory {
    // Provides methods that return implementation class objects
    public static UserDao getUserDao() {
        return new UserDaoImpl();
    }
}

2. Call the dao layer in the service layer.

UserDao dao = BeanFactory.getUserDao();
dao.add();

But in doing so, we will find that the interface and implementation classes are decoupled, but the service layer and factory classes are coupled again.
This leads to the underlying implementation principle of IoC: factory design pattern + reflection + XML configuration file.

1. XML file configuration

<bean id="userDao" class="edu.zy.dao.impl.UserDaoImpl" />

2. Create a factory class, provide a method to return the implementation class object in the factory class, use SAX to parse the configuration file, get the corresponding class attribute value according to the id attribute value in the tag bean, and use reflection to create the implementation class object.

public class BeanFactory {
    public static Object getBean(String id) {
        // 1. Use SAX to parse the content of the configuration file
        // Get the class attribute value directly from the id value userDao
        String classvalue = "class Attribute value";
        // 2. Use reflection to get objects
        Class clazz = Class.forName(classvalue);
        UserDaoImpl userDaoImpl = (UserDaoImpl)lazz.newInstance();
        return userDaoImpl;
    }
}

Summary:

IoC decoupling practice using Spring

File directory (you can compare it when creating files later):

1. Preliminary preparation - prepare the development package for spring
Official website: http://spring.io/
Download address:
http://repo.springsource.org/libs-release-local/org/springframework/spring

2.1. Create persistence layer interface and implementation class

/**
 * Persistent layer interface of account
 */
public interface IAccountDao {

    /**
     * Simulated save account
     */
    void saveAccount();
}
/**
 * Persistence layer implementation class of account
 */
public class AccountDaoImpl implements IAccountDao {

    public  void saveAccount(){

        System.out.println("Saved account");
    }
}

2.2 create business layer interfaces and implementation classes

/**
 * Interface of account business layer
 */
public interface IAccountService {

    /**
     * Simulated save account
     */
    void saveAccount();
}

/**
 * Business layer implementation class of account
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao ;

    public AccountServiceImpl(){
        System.out.println("Object created");
    }

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

3. Create a new XML file in resources (my name is bean.xml, as long as the name is not Chinese), and copy the following code:

<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>

Note: at this time, some people may not be able to load the spring website, and the code will be red. My solution is: (you can try, because there are many kinds of errors, sometimes this method won't work...)

4. Let spring manage resources and configure service and dao in the above 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">

    <!--Leave the creation of objects to spring To manage-->
    <!-- to configure service --> 
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    <!-- to configure dao --> 
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>

5. Test whether the configuration is successful

public static void main(String[] args) {
        //1. Get the core container object
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\zhy\\Desktop\\bean.xml");
        //2. Get Bean object according to id
        IAccountService as  = (IAccountService)ac.getBean("accountService");
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);

        System.out.println(as);
        System.out.println(adao);
        as.saveAccount();

result:

Keywords: Java Spring Back-end ioc

Added by Noumes on Sun, 02 Jan 2022 13:55:52 +0200