[Spring] OCP, DIP principle, IoC idea and dependency injection DI key knowledge summary

1. Spring Apocalypse:

1.1 OCP principles:

  • What is OCP?

  • OCP is the most basic principle of the seven software development principles: the principle of opening and closing

  • Open to what? Open to extensions

  • Closed to what? Closed to modification

  • The OCP principle is the core and the most basic, and the other six principles serve this principle

  • What is the core of the OCP opening and closing principle?

  • As long as you do not modify the previously written code when extending the function , then you are in line with the OCP principle

  • Conversely, if the previous code is modified when the system function is expanded, then the design will fail and violate the OCP principle.

  • When expanding the system function, if the previously stable program is moved and the previous program is modified, all the previous programs need to be tested by the program, which is very troublesome.

1.2 Dependency Inversion Principle (DIP Principle):

  • What is Dependency Inversion Principle?

  • Program to the interface, program to the abstract, not to the concrete

  • What is the purpose of the Dependency Inversion Principle?

  • Reduce program coupling and improve scalability

  • What is Compliant Dependency Inversion?

  • The upper (the code of the business layer) does not depend on the lower (the code of the persistence layer), which is in line with dependency inversion

  • What is non-violating dependency inversion?

  • Relying on the top and the bottom is a violation of

  • As long as the lower code is changed, the upper will be implicated

// 业务层
public class UserServiceImpl implements UserService {
    // 修改之前: 违背了依赖倒置原则
	private UserDao userDao = new UserDaoImplForMySQL();
    
    // 修改之后: 不违背了,但是如果不new的话, userDao=null
    private UserDao userDao; // 直接写个接口
    
    @Override
    public void deleteUser(){
        // null调用方法就会空指针异常
        userDao.deleteById();
    }
}

1.3 Inversion of control IoC idea:

  • The current program design obviously violates OCP and DIP, what should I do?

  • The programming idea of ​​"inversion of control" can be used to solve the problem

  • What is Inversion of Control?

  • Inversion of Control: IoC (Inversion of Control)

  • What is an inversion?

  • The reverse is two things

  • The first thing: I don't use hard-coded methods to create new objects in the program (the rights to new objects are handed over)

  • The second thing: I don't use hard-coded methods to maintain the relationship between objects in the program (all the maintenance between objects is handed over), such as the following code:

// 业务层
public class UserServiceImpl implements UserService {
     // 到底是UserDaoImplForMySQL还是UserDaoImplForOracle
     // 	和UserServiceImpl产生关系, 我不管了
    private UserDao userDao = new UserDaoImplForMySQL();   
    private UserDao userDao = new UserDaoImplForOracle();
    
    @Override
    public void deleteUser(){   
        userDao.deleteById();
    }
}
  • Inversion of control: It is a programming idea , or a new type of design pattern, which is not included in the scope of design patterns in GoF23 due to its relatively new appearance.

  • The role of inversion of control: make the program conform to the OCP principle and the DIP principle

1.4 Dependency injection DI:

  • The Spring framework implements the idea of ​​inversion of control IoC

  • The Spring framework can help you with new objects

  • The Spring framework can help you maintain the relationship between objects and objects

  • Spring is a container that implements the idea of ​​IoC

  • There are many ways to implement inversion of control, the more important one is called: Dependency Injection (DI for short)

  • Inversion of control is an idea, and dependency injection is the concrete realization of this idea

  • Dependency injection DI includes two common ways:

  • The first one, set injection (execute set method to assign value to property)

  • The second type, construction method injection (execute the construction method to assign values ​​to the properties)

public class UserServiceImpl implements UserService{

    private UserDao userDao;

    // set注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    // 构造方法注入
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void deleteUser() {
        userDao.deleteById();
    }
}
  • What does "dependency" mean in dependency injection? What does "injection" mean?

  • Dependency: the relationship between objects and objects (A object has B, B object has C)

  • Injection: It is a means by which the A object and the B object can have a relationship

  • Dependency injection: The relationship between object A and object B is maintained by means of injection, and injection includes: set injection and construction injection

  • Spring completes Bean management through dependency injection

  • What Bean Management says is:

  • Bean object creation

  • Assignment of properties in Bean objects (or maintenance of relationships between Bean objects)

2. Spring overview:

  • Spring is a lightweight control inversion IoC and aspect-oriented AOP container framework

  • Spring originally appeared to solve the problems of EJB's bloated design and difficulty in testing

  • Spring is born for simplification, so that programmers only need to focus on the realization of core business, and no longer pay attention to non-business logic code (transaction control, security log, etc.)

  • What kind of data structure does Spring store the created objects in?

  • Map<String,Object>

  • Does the class configured in the configuration file have to be custom? You can use the class in the JDK, for example: java.util.Date?

// xml
<bean id="dateBean" class="java.util.Date"/> // 不是

3. The first spring program:

  • How does Spring instantiate objects?

  • By default, spring uses the reflection mechanism to call the no-argument construction method of the class to instantiate the object . The implementation principle is as follows:

  • class clazz = Class.forName("com.powernode.bean.User");

  • Object obj = clazz.newInstance();

  • The super parent interface of the ApplicationContext interface is: BeanFactory (translated as a Bean factory, which is a factory object that can produce Bean objects)

  • BeanFactory is the top-level interface of the IoC container

  • The bottom layer of Spring's IoC container actually uses the factory pattern

  • How is Spring's underlying IoC implemented?

  • XML parsing + factory pattern + reflection mechanism

  • ApplicationContext is a subclass of BeanFactory, why use ApplicationContext?

  • Because it has more methods and more functions

// xml
    <!-- 配置bean, 这样spring才可以帮助我们管理这个对象   -->
    <!-- bean标签的俩个重要属性:
                id: 是这个bean的身份证号, 不能重复, 是唯一标识
                class: 必须填写类的全路径, 全限定类名(带包名的类名)
    -->
    <bean id="userBean" class="com.powernode.bean.User"/>

// @Test
public void testFirstSpringCode() {
    // 第一步: 获取Spring容器
    // ApplicationContext 翻译为: 应用上下文, 其实就是Spring容器
    // ApplicationContext 是一个接口
    // ApplicationContext 接口下有很多实现类, 其中一个就是ClassPathXmlApplicationContext
    // ClassPathXmlApplicationContext 专门从类路径当中加载spring配置文件的一个spring上下文对象
    // 这行代码只要执行, 就相当于启动了spring容器, 解析spring.xml文件, 并且实例化所有的bean对象, 放到bean容器当中
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
 	// 下面的代码也没问题:
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring.xml");
        
    // 第二步: 根据bean的id从spring容器中获取这个对象
    // 如果id不存在, 不会返回null, 会报错
    Object userBean = ctx.getBean("userBean");
    // 不想强制类型转换, 可以使用下面的代码: (通过第二个参数, 指定返回的bean的类型)
    User userBean1 = ctx.getBean("userBean", User.class);

    System.out.println(userBean);
}
  • Note that the object is not created when the getBean() method is called . When the following code is executed, the object will be instantiated and the parameterless construction will be called

// @Test
public void testBeginInitbean(){
    // 注意不是在调用getBean()方法的时候创建对象, 执行以下代码的时候, 就会实例化对象
    new ClassPathXmlApplicationContext("spring.xml");
}

Guess you like

Origin blog.csdn.net/qq_68993495/article/details/128893014