Spring -- [quick start, configuration file, dependency injection and API]

Posted by johnc71 on Tue, 19 Oct 2021 02:28:46 +0200

catalogue

Introduction to Spring:

1. Basic concepts of Spring:

2. Advantages of Spring:

3. Spring architecture

Spring quick start

Spring configuration file

1. Bean tag basic configuration

2. Bean tag range configuration

3. Bean lifecycle configuration:

4. There are three ways to instantiate a Bean

5. Introduction to Bean dependency injection

6. Dependency injection analysis of Bean

7. Dependency injection concept of Bean

8. Dependency injection method of Bean

9. Data type of Bean dependency injection

10. Introduce other configuration files (sub module development)

Summary: key points of knowledge

Spring related API s

1. Inheritance system of ApplicationContext

2. Implementation class of ApplicationContext

3. Use of getBean() method

4. Key API s of Spring

Introduction to Spring:

1. Basic concepts of Spring:

Spring is a lightweight open source framework for layered Java SE/EE application full stack, with loC(Inverse Of Control) and AOP (Aspect Oriented Programming) as the kernel.
It provides many enterprise application technologies such as the presentation layer SpringMNC, the persistence layer spring JDBC template and the 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 open source framework for Java EE enterprise applications.

2. Advantages of Spring:

1) Convenient decoupling and simplified development
Through the loC container provided by Spring, the dependencies between objects can be controlled by Spring to avoid excessive coupling caused by hard coding. 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 be realized with traditional OOP can be easily realized through AOP.
3) Declarative transaction support
It can free us from the tedious transaction management code and flexibly manage transactions in a declarative way
Improve 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) Convenient integration of various excellent frameworks
Spring supports 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 API (such as JDBC, JavaMail, remote call, etc.), which greatly reduces the difficulty of using these APIs.
7) Java source code is a classic learning example
Spring's source code design is exquisite, the structure is clear, and the ingenuity is unique. It everywhere reflects the master's flexible use of Java design patterns and his profound attainments in Java technology. Its source code is not intended to be an example of best practices in Java technology.

3. Spring architecture

spring official website: Spring | Home

Spring quick start

  Spring program development steps

(1) Import the coordinates of the basic package developed by Spring

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

(2) Write Dao interface and implementation class

Interface:
public interface UserDao {
    public void save();
}

Implementation class:
public class  UserDaoImpl implements UserDao {
@Override
public void save(){
       System.out.println("UserDao save Method Is running....");
}
}

(3) Create Spring core 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">
</beans>

(4) Configure UserDaolmpl in the 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">

<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl"></bean>
</beans>

(5) Use Spring's API to get Bean instances

    @Test
    public void test1(){
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        userDao.save();
}

Spring configuration file

1. Bean tag basic configuration

The configuration object is created by Spring.
By default, it calls the parameterless constructor in the class. If there is no parameterless constructor, it cannot be created successfully.
Basic properties:
ID: the unique identifier of the bean instance in the Spring container
Class: the fully qualified name of the bean

2. Bean tag range configuration

Scope: refers to the scope of the object. The values are as follows:

  1) When the value of scope is singleton
         Number of instantiations of Bean: 1
         Bean instantiation timing: instantiate the configured bean instance when the Spring core file is loaded
         Bean lifecycle:
                 Object creation: when the application loads and creates a container, the object is created
                 Object running: the object remains alive as long as the container is
                 Object destruction: when the application unloads and destroys the container, the object is destroyed
2) When the value of scope is prototype
         Number of Bean instantiations: multiple
         Instantiation timing of Bean: instantiate Bean when calling getBean() method
         Bean lifecycle:
                 Object creation: creates a new object instance when using an object
                 Object running: as long as the object is in use, it will always be alive
                 Object destruction: when an object is not used for a long time, it is recycled by the Java garbage collector

3. Bean lifecycle configuration:

Init method: Specifies the name of the initialization method in the class
Destroy method: Specifies the name of the destroy method in the class

4. There are three ways to instantiate a Bean

(1) Instantiate using the parameterless construction method
   It will create class objects according to the default parameterless constructor. If there is no default parameterless constructor in the bean, the creation will fail

<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl"></bean>

(2) Factory static method instantiation
   The static method of the factory returns the Bean instance

//Create a static factory
public class StaticFactory {
//Static method
    public static UserDao getUserDao(){
        return new UserDaoImpl();
    }
}

Profile:

<bean id="userDao" class="com.longdi.factory.StaticFactory" factory-method="getUserDao"></bean>

(3) Factory instance method instantiation
  The non static method of the factory returns a Bean instance

public class DynamicFactory {
    public UserDao getUserDao(){
        return new UserDaoImpl();
    }
}

Profile:

    <bean id="factory" class="com.longdi.factory.DynamicFactory"></bean>
    <bean id="userDao" factory-bean="factory" factory-method="getUserDao"/>

5. Introduction to Bean dependency injection

(1) Create UserService. UserService calls the save() method of UserDao internally

public class UserServiceImpl implements UserService {
 public void save(){
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        userDao.save();
}
}

(2) Give Spring the right to create UserServicelmpl

<bean id="userService" class="com.longdi.service.impl.UserServiceImpl">

(3) Obtain UserService from Spring container for operation

       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.save();

6. Dependency injection analysis of Bean

At present, both UserService instances and UserDao instances exist in the Spring container. The current practice is to obtain UserService instances and UserDao instances outside the container, and then combine them in the program.

  Because both UserService and UserDao are in the Spring container, and the final program directly uses UserService, you can set UserDao inside UserService in the Spring container.

7. Dependency injection concept of Bean

Dependency injection: it is the concrete implementation of the Spring framework core IOC.
When writing the program, the creation of objects is handed over to Spring through control inversion, but there can be no dependency in the code. IOC decoupling only reduces their dependencies, but it will not eliminate them. For example, the business layer will still call the methods of the persistence layer.
After using Spring, Spring can maintain the dependency between the business layer and the persistence layer. Simply put, it means waiting for the framework to transfer the persistence layer object to the business layer without getting it ourselves.

8. Dependency injection method of Bean

How to inject UserDao into UserService?     Two methods: set method and construction method

(1) set method injection

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public void setUserDao(UserDao userDao) 
      {
                this.userDao = userDao;
      }

    @Override
    public void save() {
        userDao.save();
    }
}
<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl">

<bean id="userService" class="com.longdi.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

The essence of P namespace injection is also set method injection, but it is more convenient than the above set method injection, which is mainly reflected in the configuration file as follows: first, you need to introduce P namespace:

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

Secondly, the injection method needs to be modified

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

(2) Construction method injection

        Create parametric structure

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserServiceImpl() {
    }

    @Override
    public void save() {
        userDao.save();
    }
}

         Configure the Spring container to inject when calling parameterized constructs

<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.longdi.service.impl.UserServiceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>

9. Data type of Bean dependency injection

(1) Reference data type

      The reference data type is that the previous operations are injected with the reference of the UserDao object

(2) Common data type

public class UserDaoImpl implements UserDao {
    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 ( "UserDao save method running . . . ." );
)
<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl">
<propertyname="name" value="Long di"></property>
<property name="age" value="18"></property>
</bean>

(3) Collection data type

        1. Injection of set data type (list < string >)

public class UserDaoImpl implements UserDao {
    private List<String> strList;
    public void setStrList(List<String> strList){
    this.strList = strList;
    }
    public void save () {
    system.out.println (strList) ;
    system.out.println ( "UserDao save method running . . . ." );
}
}
<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl">
<property name="strList" >
<list>
    <value>aaa</value>
    <value>bbb</value>
    <value>ccc</value>
</list>
</property>
</bean>

         2. Injection of set data type (list < user >)

public class UserDaoImpl implements UserDao {
    private List<User> userList;
    public void setUserList (List<User> userList) {
    this.userList = userList;
    }
    public void save (){
    system.out.println (userList) ;
    system.out.println ( "UserDao save method running . . . ." );
)
<bean id="u1" class="com.longdi.domain.User" / >
<bean id="u2" class="com.longdi.domain.User" / >
<bean id="userDao" class="com.longdi.dao.imp1. UserDaoImpl">
    <property name="userList">
        <list>
           <bean class=" com.longdi.domain.User" / >
           <bean class=" com.longdi.domain.User" />
           <ref bean="u1" />
           <ref bean="u2"/>
        </list>
    </property>
</bean>

        3. Injection of set data type (map < string, user >)

public class UserDaoImpl implements UserDao {
    private Map<String,User> userMap;
    public void setUserMap(Map<String,User> userMap ) {
    this. userMap = userMap;
    public void save () {
    system.out.println (userMap ) ;
    system.out.println ("UserDao save method running . . .." ) ;
}
<bean id="u1" class="com.longdi.domain.User" / >
<bean id="u2" class="com.longdi.domain.User" / >
<bean id="userDao" class="com.longdi.dao.impl.UserDaoImpl">
<property name="userMap" >
<map>
    <entry key="user1" value-ref="u1" / >
    <entry key="user2" value-ref="u2"/ >
</map>
</property>
</bean>

        4. Injection of collection data types (Properties)

public class UserDaoImpl implements UserDao {
    private Properties properties;
    public void setProperties(Properties properties){
    this.properties = properties;
    )
    public void save () {
    system.out.println (properties ) ;
    System.out.println ( "UserDao save method running . . . ." ) ;
    }
    )
<bean id="userDao" class="com.longdi.dao.impl .UserDaoImpl">
<property name="properties" >
<props>
    <prop key="p1">aaa</prop>
    <prop key="P2">bbb</prop>
    <prop key="p3">ccc</prop>
</props>
</property>

10. Introduce other configuration files (sub module development)

  In actual development, there are many Spring configurations, which leads to the complexity and volume of Spring configuration. Therefore, some configurations can be disassembled into other configuration files, and loaded in the Spring main configuration file through the import tag

<import resource="applicationContext-xxx. xml"/>

Summary: key points of knowledge

Key configuration of Spring
< bean > tag
         id attribute: the unique identifier of the Bean instance in the container. Duplicate is not allowed
         class attribute: the fully qualified name of the Bean to be instantiated
         Scope attribute: the scope of a Bean, usually singleton (default) and prototype
        < Property > tag: Property injection
                 Name attribute: attribute name
                 Value attribute: the injected common attribute value
                 ref attribute: injected object reference value
                < List > tag
                < Map > label
                < Properties > tab
        < Constructor Arg > tag
< import > tag: import other spring sub files

Spring related API s

1. Inheritance system of ApplicationContext


applicationContext: interface type, which represents the application context. You can obtain the Bean object in the Spring container through its instance

 

2. Implementation class of ApplicationContext

1)ClassPathXmlApplicationContext
It loads the configuration file from the root path of the class. This is recommended

2)FileSystemXmlApplicationContext
It loads the configuration file from the disk path. The configuration file can be anywhere on the disk.

3) AnnotationConfigApplicationContext
When configuring container objects with annotations, you need to use this class to create a spring container. It is used to read annotations.

3. Use of getBean() method

public Object getBean ( String name)throws BeansException {
        assertBeanFactoryActive() ;
        return getBeanFactory ( ).getBean (name);
}
public <T> T getBean(Class<T> requiredType) throws BeansException {
    assertBeanFactoryActive ( ) ;
    return getBeanFactory().getBean (requiredType) ;

Where, when the data type of the parameter is a string, it means that the Bean instance is obtained from the container according to the Bean id, and the return is Object, which needs to be forced. When the data type of the parameter is Class, it means that Bean instances are matched from the container according to the type. When there are multiple beans of the same type in the container, this method will report an error.
 

ApplicationContext applicationContext = new classPathxmlApplicationContext ("applicationContext.xm1")
UserService userService1 = (Userservice)applicationContext.getBean ("userService");
UserService userService2 = applicationcontext.getBean(UserService.class);

4. Key API s of Spring

ApplicationContext app = new ClasspathXmlApplicationContext ( "xml file")
app. getBean ("id")
app.getBean (Class)

Topics: Spring