[Spring ioc control inversion]

1 spring introduction

1 What is a framework

  • Originated from architecture, affiliated with civil engineering, and later developed into the field of software engineering

  • Software engineering framework: proven, functional, semi-finished software

    • Proven (many people agree with him)

    • Have certain functions (have functions and can be used)

    • Semi-finished product (similar to dough)

2 The role of the framework

Improve development efficiency
Enhance reusability
Provide writing specifications
Save maintenance costs
Decoupling underlying implementation principles

3 What is Spring

Spring is a layered JavaSE/EE application full-stack (one-stop), lightweight open source (free), semi-finished product (implements some functions, but not all functions) The framework takes IOC (Inverse Of Control: Inversion of Control) and AOP (Aspect Oriented Programming: Aspect-oriented Programming) as its core.

Layering: view layer, logic layer, persistence layer

full-stack: Basically, spring can be used to solve any needs in development. It is a one-stop service and all components in development can be provided.

Lightweight: Compared with heavyweight, EJB (complex and cumbersome, see the development history chart)

4 Spring’s architecture (important)

spring official website: spring.io

Spring Framework: It is the core of the framework spring

ORM is mybatis and JPA are of the same order.

5 Spring’s development history

6 Spring Advantages

  • Convenient decoupling and simplified development (dependency injection and IOC)

  • Conveniently integrates various excellent frameworks (supports framework integration and leaves compatible interfaces for other frameworks)

  • Facilitates program testing (test underlying support)

  • Aspect programming support (AOP)

  • Declarative transaction support @Transactional (annotations and transactions)

  • Reduce the difficulty of using JavaEE API (easy to get started, simple operation)

2 IOC inversion control (important to ask in interviews)

1 Concept (spring is used as a container, whoever puts it in takes it)

  • The full name of IoC is Inversion of Control, which translates as “inversion of control”. It also has an alias called DI (Dependency Injection), which is dependency injection.
  • The essential function is: The Spring IOC container is responsible for the life cycle of objects and the relationship between objects
  • If you want to learn spring well, you must always think about it. The essence of spring is a container, a container for Java objects. Java objects are also called bean objects in the spring container.

Maven management download rack package

apache-maven-3.6.3->conf->settings.xml

Manage the warehouse of rack packages (line 55) to facilitate downloading of rack packages (similar to a network disk with VIP enabled)

mirror: Mirror file (line 159)

Configuring the image is to configure the download path to accelerate the image

Mirror files, also known as image files, are similar to compressed files. They make a specific series of files into a single file in a certain format to facilitate users to download and use.

3 Getting Started Case

  • Create project

    (1.Choose maven

    (2.Archetype select quickstart

    (3. Open Advanced Settings

    (4.Groupld com.xinzhi and then click Create

    (5.file->settings->build->build tools->maven

    (6. Override home path:apache-maven-3.6.3

    (7.settings file:apache-maven-3.6.3-> conf ->settings.xml

    (8.apply ok

    (9. There is Maven in the vertical frame on the far right. Refresh it.

  • Let’s talk about the pom.xml file

    The group id is the package name

  • 1 Import the basic package coordinates developed by Spring

  • 2 Write Dao interface and implementation class

  • 3 Create Spring core configuration file

  • 4 Configure UserDaoImpl in the Spring configuration file

  • 5 Use Spring’s API to obtain a Bean instance

1 Import the basic package coordinates developed by Spring **Remember to refresh it** (the corresponding architecture diagram is visible)

Put the following configuration information in pom.xml

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!--Import spring's context coordinates, context depends on core, beans, expression-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <version>1.0</version>
    </dependency>
  </dependencies>

2 Write Dao interface and implementation class

Create the folder src/main/java com.xinzhi and build a dao package

public interface IUserDao {<!-- -->
    void say();
}


public class UserDaompl implements IUserDao {<!-- -->
    public void say() {<!-- -->
        System.out.println("Hello");
    }
}

3 Create Spring core configuration file

resources file

What if there is no yellow mark on the lower right?

(1. Right-click Mark Directicy as what to mark the folder for?

(2.Select Research Root

(3. Right click new

(4.Select XML Configuration File

(5.Spring Config

(6. The file name begins with application. The first letter is lowercase application.xml

4 Configure UserDaoImpl in the Spring configuration file

There is no requirement to be able to memorize the configuration file, but you need to be able to see roughly what it is, at least be able to stick it, and know which lines to use and which lines to use cv.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="user" class="com.xinzhi.dao.impl.UserDaompl" />

</beans>

5 Use Spring’s API to obtain a Bean instance

public static void main( String[] args ) {<!-- -->
     //new ClassPathXmlApplicationContext(configuration file) + .var completion
        //Create a context context container to put the bean object configuration file
        //new configuration file
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //Get the bean object storing UserDaompl in the configuration file (container)
        UserDaompl bean = context.getBean(UserDaompl.class);
        bean.say();
}

4 Bean tag description

![The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly](https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=spring.assets/ image-20211003092724289.png &pos_id=img-vdieiVqe-1693911445441

  • id: the unique identification of the Bean instance in the Spring container
  • class: Fully qualified name of the Bean
  • scope: scope configuration, spring defaults to singleton mode.

5 Life Cycle (memorize important interview questions)

1) When the value of scope is singleton** (system default)single mode
Number of Bean instantiations: 1
Bean instantiation timing: When the Spring core file is loaded, instantiate the configured Bean instance
Bean life cycle:
**
Object creation: When the application is loaded and the container is created, the object is created** (the object is created as soon as the container starts (the moment the main method runs))**
Object running: As long as the container is there, the object is alive (The container is alive)
Object destruction: When the application is uninstalled and the container is destroyed, the object is destroyed.

The same object is retrieved several times, which can be proved by multiple bean objects. The printed address value is the same.

 UserDaompl userDao1 = context.getBean(UserDaompl.class);
 System.out.println(userDao1);
 UserDaompl userDao2 = context.getBean(UserDaompl.class);
 System.out.println(userDao2);

2) Multiple instance mode when the value of scope is prototype
Number of Bean instantiations: multiple
Bean instantiation timing: Bean is instantiated when the getBean() method is called
Object creation: When using an object, create a new object instance** (the container is empty when starting, and when the getbean method is called, the corresponding bean is created)**
Object running: As long as the object is in use, it remains alive.
Object destruction: When an object is not used for a long time, it is recycled by Java’s garbage collector (jvm gc garbage collection) (similar to ordinary objects)

It is not the same object after being retrieved several times. This can be proved by using multiple bean objects. The printed address values are different.

Note: The above bean object instantiations are all spring calls of the parameterless construction method of the object. (There are two other methods that have never been used in development: factory instance method and factory static method)

3 DI dependency injection (important to ask in interviews)

Two methods: set injection and construction injection (in the blue box of the understanding section in the second section above, just know what it is)

To understand dependency injection, you need to split this concept into two parts, dependency (relationship) and injection (assignment of one to another).

The process of assigning values to objects in a container is actually called dependency injection

Dependency: The relationship between two objects. For example, if a service wants to call a dao method, then the service needs a dao object. This is a dependency.

Injection: It is the process of giving the dao object to the service object. In the spring container, the injection is completed by the container.

  • As the name implies, there must be a set method. Note that the injection method is set, but it is executed by the spring container.

  • Create a new IUserService combined with UserServiceImpl to create a services package

public interface IUserService {<!-- -->
    void save();
}

public class UserServiceImpl implements IUserService {<!-- -->
    //Assign value to userDao through bean
    private IUserDao userDao;
//The set method is a method of passing values. You need to add the set method, otherwise a null pointer exception will be reported.
    public void setUserDao(IUserDao userDao) {<!-- -->
        this.userDao = userDao;
    }

    public void save() {<!-- -->
        userDao.say();
    }
}
    
<bean id="user" class="com.xinzhi.dao.impl.UserDaompl" />
        
    <bean id="userService" class="com.xinzhi.service.impl.UserServiceImpl">
        //Property is injection. It depends on the user object in UserDao. Inject the user object into userDao to generate a new UserServiceImpl object.
  <!-- The meaning of the property attribute, the object is UserServicempl and has a userDao attribute, name is userDao. These two userDao are the same thing -->
        //ref reference refers to the object that already exists in the container. Take it and use it directly. Take it and assign values to the properties.
        <property name="userDao" ref="user"/>
</bean>

 public static void main( String[] args ) {<!-- -->
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl bean = context.getBean(UserServiceImpl.class);
        bean.save();
    }

4 Annotation development

  • Spring’s original annotations

  • Development steps

    1 Scan the components under the package (annotations)

    ?

    2 Add annotations

    @Component("user")
    public class User {<!-- -->
        @Value("1")
        private int id;
        @Value("Zhang Zuorong")
        private String username;
        @Value("20")
        private int age;
        //set get method
    }
    
    
    /**
     *dao layer annotation
     */
    @Repository("userDao")
    public class UserDaompl implements IUserDao {<!-- -->
    
        @Autowired
        private User user;
    
        public void say() {<!-- -->
            System.out.println(user);
            System.out.println("UserDao save method running....");
        }
    }
    
    
    /**
     * service annotation
     */
    @Service("userService")
    public class UserServiceImpl implements IUserService {<!-- -->
    // @Autowired
    // @Qualifier("userDao")
        @Resource(name = "userDao")
        private IUserDao userDao;
    
        public void save() {<!-- -->
            userDao.say();
        }
    }
    
     public static void main( String[] args ) {<!-- -->
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            UserServiceImpl bean = context.getBean(UserServiceImpl.class);
            bean.save();
        }
    
    

    result:

Note: Autowired annotations are generally used, because spring is in singleton mode by default, so it is rarely used in conjunction with Qualifier. Resource will throw an exception if the injected object does not exist