Spring-IOC container

Three commonly used implementation classes of ApplicationContext

  1. ClassPathXmlApplicationContext: It can load configuration files under the classpath, and the configuration files must be under the classpath. If you are away, you can't load it. (More commonly used)
  2. FileSystemXmlApplicationContext: It can load configuration files in any path of the disk (must have access rights)
  3. AnnotationConfigApplicationContext: It is used to read annotations to create a container.

Problems caused by the two interfaces of the core container

  1. ApplicationContext: (Singleton object is applicable)
    1. When it builds the core container, its strategy for creating objects is to use immediate loading. In other words, as soon as you finish reading the configuration file, you will create the objects configured in the configuration file.
  2. BeanFactory: (applicable to multiple objects)
    1. When it builds the core container, its strategy for creating objects is to use lazy loading. In other words, when is the object obtained based on the Id, and when is the object actually created.

Dependency injection in spring

  1. Dependency Injection: Dependency Injection
  2. The role of IOC: reduce the coupling between programs (dependency)
  3. Dependency management: all will be maintained by spring in the future
  4. In the current class, objects of other classes are used, provided by spring. We only need to explain the maintenance of dependencies in the configuration file, which is called dependency injection.
  5. Dependency injection
    1. There are three types of data that can be injected
      1. Basic types and String
      2. Other bean types (beans configured in configuration files or annotations)
      3. Complex type/collection type
    2. Ways of injection: there are three
      1. Use the constructor to provide
        1. Use label: constructor-arg
        2. Where the label appears: inside the bean label
        3. Attributes in the label:
          1. type: used to specify the data type of the injected data, which is also the type of one or some parameters in the constructor
          2. index: Used to assign the data to be injected to the parameter at the specified index position in the constructor. The position of the index starts from 0
          3. name: Used to assign the parameter assignment of the specified name in the constructor (commonly used)
          4. value: used to provide basic type and String type data
          5. ref: used to specify other bean type data. It refers to the bean object that appeared in the spring IOC core container.
        4. Advantages: When obtaining a bean object, injecting data is a necessary operation, otherwise the object cannot be created successfully.
        5. Disadvantages: The instantiation method of the bean object has been changed, so that when we create the object, if the data is not used, we must also provide it.
      <bean id="userService" class="com.whut.service.imp.UserServiceImp" scope="singleton" init-method="init" destroy-method="destory">
          <constructor-arg name="string" value="张三"></constructor-arg>
          <constructor-arg name="integer" value="12"></constructor-arg>
          <constructor-arg name="date" ref="now"></constructor-arg>
      </bean>
      <bean id="now" class="java.util.Date"></bean>
      <bean id="userDao" class="com.whut.dao.imp.UserDaoImp"></bean>
      
      Construct a method with parameters in UserServiceImp
      private String string;
      private Integer integer;
      private Date date;
      public UserServiceImp(String string, Integer integer, Date date){
              
              
          this.string = string;
          this.integer = integer;
          this.date = date;
      }
      
      1. Use the set method to provide (more commonly used)
        1. Involved tags: property
        2. Appearance position: inside the bean tag
        3. Label attributes
          1. name: Used to assign a value to the parameter with the specified name in the constructor (commonly used).
          2. value: used to provide basic type and String type data.
          3. ref: used to specify other bean type data. It refers to the bean object that appeared in the spring IOC core container.
        4. Advantages: There are no clear restrictions when creating objects, you can directly use the default constructor.
        5. Disadvantages: If a member must have a value, the set method cannot guarantee certain injection, and the set method may not be executed when the object is obtained.
        <bean id="userService" class="com.whut.service.imp.UserServiceImp" init-method="init" destroy-method="destory">
            <property name="string" value="李四"></property>
            <property name="integer" value="21"></property>
            <property name="date" ref="now"></property>
        </bean>
        <bean id="now" class="java.util.Date"></bean>
        <bean id="userDao" class="com.whut.dao.imp.UserDaoImp"></bean>
        
        Generate setter method in UserServiceImp
        private String string;
        private Integer integer;
        private Date date;
        
        public void setString(String string) {
                  
                  
        this.string = string;
        }
        
        public void setInteger(Integer integer) {
                  
                  
            this.integer = integer;
        }
        
        public void setDate(Date date) {
                  
                  
            this.date = date;
        }
        
        1. Complex type/collection type injection
          1. Label
            list array set used to inject the List structure collection
          2. The label
            map props used to inject the Map structure collection
          3. Same structure, labels can be interchanged
        <property name="myStrs">
        <array>
            <value>AAA</value>
            <value>张三</value>
            <value>A12</value>
        </array>
        </property>
        
        <property name="myLsit">
            <list>
                <value>AAA</value>
                <value>张三</value>
                <value>A12</value>
            </list>
        </property>
        
        <property name="mySet">
            <set>
                <value>AAA</value>
                <value>张三</value>
                <value>A12</value>
            </set>
        </property>
        
        <property name="myMap">
            <map>
                <entry key="testA" value="AAA"></entry>
                <entry key="name" value="张三"></entry>
                <entry key="age">
                    <value>13</value>
                </entry>
            </map>
        </property>
        
        <property name="myProperties">
            <props>
                <prop key="学历">高中</prop>
                <prop key="years">2019</prop>
            </props>
        </property>
        
      2. Provided with annotations
        1. bean.xml configuration
          1. Tell Spring the package to scan when creating the container. The tags required for configuration are not in the constraints of beans, but in a name space and constraints named context.
            <?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.xsd">
            
                <context:annotation-config/>
            
            </beans>
            
        2. Used to create objects: their role is the same as a <bean> tag written in the xml configuration file
          1. Component
            1. Role: used to store the current class object in spring
            2. Attributes:
              1. value: used to specify the id of the bean. When we do not write, its default value is the current class name, and the first letter is changed to lowercase
          2. Controller: Generally used in the presentation layer
          3. Service: generally used in the business layer
          4. Repository: generally used in the persistence layer
          5. The functions and attribute values ​​of the above three annotations are exactly the same as those of Component. The three of them are that the Spring framework provides us with clear annotations for the use of the three layers, which makes our three-layer objects more clear.
        3. Used to inject data: their role is the same as a <property> tag written in the xml configuration file
          1. Autowired
            1. Function: Automatically inject according to the type, as long as there is only one bean object type in the container that matches the type of the variable to be injected, the injection can be successful. If there is no bean type in the IOC container that matches the type of the variable to be injected, an error is reported. If there are multiple matching types in the IOC container, the injection will be performed according to the variable name. If there is no matching variable name, the injection will fail.
            2. Appearance position: it can be in variable or method
            3. Details: When using annotation injection, the set method is not necessary
          2. Qualifier
            1. Function: Inject according to the name on the basis of injecting in the class. It cannot be used alone when injecting class members. But when injecting method parameters, you can
            2. Attributes
              1. value: used to specify the id of the injected bean.
          3. Resource
            1. Function: Inject directly according to the id of the bean. It can be used alone
            2. Attributes
              1. name: used to specify the id of the bean
          4. The above three injections can only inject data of other bean types, while the basic types and String types cannot be implemented using the above annotations. In addition, the injection of collection types can only be achieved through xml.
          5. value
            1. Role: used to inject basic type and String type data
            2. Attributes:
              1. value: used to specify the value of the data, it can use spEL in spring (that is, spring el expression)
              2. How to write spEL: ${Expression}
        4. Used to change the scope: their role is the same as a <scope> tag written in the xml configuration file
          1. scope:
            1. Role: used to specify the scope of the bean
            2. Attribute: value: specify the range of values ​​(singleton, prototype)
        5. Related to the life cycle: their role is the same as using the init-method and destroy-method tags in the xml configuration file
          1. PerDestroy: used to specify the destruction method
          2. PostConstruct: used to specify the initialization method
        6. Business Layer
        @Service("userService")
        public class UserServiceImp implements UserService {
                  
                  
        
            @Autowired
            private UserDao userDao = null;
        
            public void saveUser() {
                  
                  
                userDao.saveUser();
            }
        
        }
        
        1. Persistence layer
        @Repository("userDao")
        public class UserDaoImp implements UserDao {
                  
                  
        
            @Override
            public void saveUser() {
                  
                  
                System.out.println("保存用户1111111");
            }
        
        }
        
        1. test
         public class Client {
                  
                  
             public static void main(String[] args) {
                  
                  
                 //1.获取核心容器对象
                 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
                 //2. 根据id获取bean对象
                 UserService userService = (UserService) applicationContext.getBean("userService");
                 System.out.println(userService);
                 userService.saveUser();
             }
         }
        
        1. note
          1. @Autowired注释写在方法上方报错:Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userService’: Injection of autowired dependencies failed; nested exception is java.lang.NullPointerException
          2. Solution: write @Autowired annotation above the variable

Guess you like

Origin blog.csdn.net/qq_40857365/article/details/111307771