Spring learning notes. The first spring program is hellosppring. Spring overview, IOC implementation analysis.

1. Spring overview

1.1 INTRODUCTION

  • Spring: Spring - > brings spring to the software industry
  • In 2002, Rod Jahnson first launched the Spring framework prototype interface21 framework.
  • On March 24, 2004, the Spring framework was redesigned based on the interface21 framework and released the official version of 1.0.
  • It's hard to imagine Rod Johnson's degree. He is a doctor at the University of Sydney. However, his major is not computer, but musicology.
  • Spring concept: make the existing technology more practical It is a hodgepodge in itself, integrating the existing framework technology

Official website: http://spring.io/

Official download address: https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

1.2 advantages

  • Spring is an open source free framework, container
  • Spring is a lightweight framework, non - intrusive
  • Control inversion IoC, facing section Aop
  • Support for transaction and framework

In one sentence: Spring is a lightweight container (framework) for inversion of control (IoC) and aspect oriented (AOP).

1.3 composition

The Spring framework is a layered architecture consisting of seven well-defined modules. The Spring module is built on top of the core container, which defines how bean s are created, configured, and managed.

Each module (or component) that makes up the Spring framework can exist alone or be implemented jointly with one or more other modules. The functions of each module are as follows:

  • Core container: the core container provides the basic functions of the Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the inversion of control (IOC) pattern to separate the configuration and dependency specifications of the application from the actual application code.
  • Spring context: a 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, checksum and scheduling capabilities.
  • Spring AOP: through the configuration management feature, the spring AOP module directly integrates the aspect oriented programming functions into the spring framework. Therefore, you can easily make the spring framework manage any object that supports AOP. The spring AOP module provides transaction management services for objects in spring based applications. By using spring AOP, declarative transaction management can be integrated into applications 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. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written (such as opening and closing connections). The JDBC oriented exceptions of spring DAO follow the general DAO exception hierarchy.
  • Spring ORM: the spring framework inserts several ORM frameworks to provide ORM object relationship tools, including JDO, Hibernate and iBatis SQL Map. All of this follows spring's common transaction and DAO exception hierarchy.
  • Spring Web module: the Web context module is built on the application context module and provides context for web-based applications. Therefore, the spring framework supports integration with Jakarta Struts. The web module also simplifies processing multipart requests and binding request parameters to domain objects.
  • Spring MVC framework: MVC framework is a full-featured MVC implementation for building Web applications. Through the policy interface, the MVC framework becomes highly configurable. MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, iText and POI.

1.4 expansion

Spring Boot and Spring Cloud

  • Spring Boot is a set of rapid configuration scaffolds of spring, which can quickly develop a single micro service based on Spring Boot;
  • Spring Cloud is implemented based on Spring Boot;
  • Spring Boot focuses on a single micro service individual that is fast and easy to integrate. Spring Cloud focuses on the overall service governance framework;
  • Spring Boot uses the concept that constraints are better than configuration. Many integration schemes have been selected for you. You can't configure without configuration. A large part of Spring Cloud is implemented based on Spring Boot. Spring Boot can use development projects independently of Spring Cloud, but Spring Cloud can't do without Spring Boot, which belongs to dependency.
  • SpringBoot plays a connecting role in SpringClound. If you want to learn SpringCloud, you must learn SpringBoot.

2. IOC Foundation

Create a new blank maven project

2.1 analysis and Implementation

Let's write a piece of code in our original way

  1. Write a UserDao interface first
public interface UserDao {
    public void getUser();
}
  1. Then write Dao's implementation class
public class UserDaoImpl implements UserDao {
    @Override
    public void getUser() {
        System.out.println("Get user data");
    }
}
  1. Then write the UserService interface
public interface UserService {
    public void getUser();
}
  1. Finally, write the implementation class of Service
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public void getUser() {
        userDao.getUser();
    }
}
  1. test
public class MyTest {
    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }
}

This is our original way. At first, everyone wrote it like this. Let's revise it now.

Add an implementation class of Userdao.

public class UserDaoMySqlImpl implements UserDao {
    @Override
    public void getUser() {
        System.out.println("MySql Get user data");
    }
}

Next, if we want to use "MySql to obtain user data", we need to modify the corresponding implementation in the service implementation class.

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoMySqlImpl();  // Modify here
    @Override
    public void getUser() {
        userDao.getUser();
    }
}

In the assumption, we add another implementation class of Userdao.

public class UserDaoOracleImpl implements UserDao {
    @Override
    public void getUser() {
        System.out.println("Oracle Get user data");
    }
}

If we want to use Oracle, we need to modify the corresponding implementation in the service implementation class. Assuming that our demand is very large, this method is not applicable at all. Each change requires a lot of code modification. The coupling of this design is too high. One hair will affect the whole body.

How can we solve it?

Instead of implementing it, we can set aside an interface where we need it. Using set, we can modify it in the code.

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    // Using set to realize
    public void setUserDao(UserDao userDao){
        this.userDao = userDao;
    }
    @Override
    public void getUser() {
        userDao.getUser();
    }
}

Now go to our test class and test;

public class MyTest {
    @Test
    public void getUser(){
        UserServiceImpl service = new UserServiceImpl();
        service.setUserDao( new UserDaoMySqlImpl() );
        service.getUser();
        //So now we want to use Oracle to implement it
        service.setUserDao( new UserDaoOracleImpl() );
        service.getUser();
    }
}

Did you find the difference? They have undergone fundamental changes, and many places are different. Think carefully. In the past, everything was controlled and created by the program, but now we control and create the object by ourselves and give the initiative to the caller. The program doesn't care how to create or implement it. It is only responsible for providing an interface.

This idea essentially solves the problem. Our 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!

2.2 IOC essence

Inversion of control (IoC) is a design idea. DI (dependency injection) is a method to realize IoC. Some people think that DI is just another way of saying IoC. In programs without IoC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded. In programs, the creation of objects is controlled by the program itself. After the control is reversed, the creation of objects is transferred to a third party. Personally, I think the so-called control reversal is the reversal of the way to obtain dependent objects.

IoC is the core content of the Spring framework. It is perfectly implemented in many ways. You can use XML configuration or annotation. The new version of Spring can also realize IoC with zero configuration.

During initialization, the Spring container reads the configuration file first, creates and organizes objects according to the configuration file or metadata, and stores them in the container. When the program is used, it takes out the required objects from the Ioc container.

When configuring beans in XML, the definition information of beans is separated from the implementation, and the annotation method can integrate the two. The definition information of beans is directly defined in the implementation class in the form of annotation, so as to achieve the purpose of zero configuration.

Inversion of control is a way to produce or obtain specific objects through description (XML or annotation) and through a third party. In Spring, the IoC container implements control inversion, and its implementation method is dependency injection (DI).

3. The first Spring program. HelloSpring

3.1 import Jar package

Note: spring needs to import commons logging for logging We use maven, which will automatically download the corresponding dependencies

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

If you are using unit tests, import the following dependencies

<!--junit-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

3.2 coding

  1. Write a Hello entity class
public class Hello {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("Hello,"+ name );
    }
}

Write a show() method to facilitate testing.

  1. Write our spring file, which is named ApplicationContext xml
<?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">
    <bean id="hello" class="com.xxc.pojo.Hello">
        <property name="name" value="spring"/>
    </bean>
</beans>
  1. test
public class MyTest {
    @Test
    public void test(){
        //Parse ApplicationContext XML file to generate and manage the corresponding Bean object
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //getBean: the parameter is the id of the bean in the spring configuration file
        Hello hello = (Hello) context.getBean("hello");
        hello.show();
    }
}

Discovery: we found that we don't need to go to the new object, but spring in the configuration file ApplicationContext XML helps us create objects. When we use objects, we only need to call them.

3.3 thinking

  • Who created the hello object? [the hello object is created by Spring]
  • How are the properties of the Hello object set? [the attributes of the Hello object are set by the Spring container]

This process is called control reversal:

  • Control: who controls the creation of objects? The objects of traditional applications are created by the program itself. After using Spring, the objects are created by Spring
  • Inversion: the program itself does not create an object, but becomes a passive receiving object
  • Dependency injection: it uses the set method to inject

IOC is a programming idea, which changes from active programming to passive reception

3.4. Modify case 1

In case 1, we add a Spring configuration file

applicationContext.xml

<?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">
    <bean id="mySqlImpl" class="com.xxc.dao.UserDaoMySqlImpl"/>
    <bean id="oracleImpl" class="com.xxc.dao.UserDaoOracleImpl"/>

    <bean id="serviceImpl" class="com.xxc.service.UserServiceImpl">
        <property name="userDao" ref="mySqlImpl"/>
    </bean>
</beans>

Note: Note: the name here is not an attribute, but the part after the set method (setUserDao), with a lowercase initial.

To reference another bean, use ref instead of value. It is equivalent to that value is an assignment and ref is a re reference.

Test!

public class MyTest {
    @Test
    public void test(){
        //Parse beans XML file to generate and manage the corresponding Bean object
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //getBean: the parameter is the id of the bean in the spring configuration file
        UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("serviceImpl");
        serviceImpl.getUser();
    }
}

Note: because in ApplicationContext The ref erence in XML is mySqlImpl, so the returned result is the result of the method in userdaomysql impl.

OK, now, we don't need to change in the program at all. To realize different operations, we only need to modify the so-called IoC in the xml configuration file. In one sentence: the objects are created, managed and assembled by Spring!

Keywords: Java Spring Back-end AOP ioc

Added by phpbeginner on Thu, 03 Feb 2022 01:01:12 +0200