Spring injection and Spring Bean assembly

1. Spring injection

      Spring injection refers to the assignment of variables when the Spring container is started to load the bean configuration.

       Two commonly used injection methods:

              1. Set value injection: inject through the set method of member variables.

        <!-- Spring IOC injection method: set value injection -->  
            <bean id="injectionService" class="com.service.InjectionServiceImpl">  
            <property name="injectionDAO" ref="injectDAO"></property>  
        </bean>  

        <bean id="injectDAO" class="com.dao.InjectionDAOImpl"></bean>  

              2. Construction injection: By injecting the class construction method.

        <!-- Spring IOC injection method: Construct injection-->  
        <bean id="injectionService" class="com.service.InjectionServiceImpl">  
            <constructor-arg name="injectionDAO" ref="injectDAO"></constructor-arg>  
        </bean>  
        <bean id="injectDAO" class="com.dao.InjectionDAOImpl"></bean>  

2. Spring Bean assembly

     2.1, Bean configuration item

          Bean configuration items include:

             1. Id: The unique identifier of the bean in the IOC container.

             2. Class: The specific class to be instantiated.

             3. Scope: The scope of the Bean.

          1. singleton: singleton, only one type exists in a bean container. If there are multiple IOC containers in the JVM container, then there are singletons, then there are multiple singletons.

                   2. prototype: A new instance is created for each request (each use), and the destory method does not take effect.

                   3. request: An instance is created for each http request and is only valid within the current request.

                   4. Session: An instance is created for each http request and is valid in the current session.

                   5. Global session: Valid in portlet-based web (prolet defines global session), if in web, the same session.

             4. Constructor arguments: Constructor arguments.

             5, Properties: Bean properties.

             6. Autowiring mode: Bean autowiring mode.

             7. Lazy-initialization mode: lazy loading mode.

             8. Initialization/destruction method: Bean initialization and destruction method.

      2.2 Bean life cycle

               Bean initialization:

               1. Initialization

                   1.  Customize the operation method after initialization/before destruction by implementing the InitializingBean/DisposableBean interface;

            public class ExampleInitializingBean implements InitializingBean{
                @Override
                public void afterPropertiesSet() throws Exception {
                }
            }

                   2. Specify the operation method to be called after initialization/before destruction through the init-method/destroy-method attribute of the <bean> element;

            <bean class="InitSequenceBean" init-method="initMethod" destroy-method="destoryMethod"></bean>

                   3. Add @PostConstruct or @PreDestroy annotation to the specified method to specify whether the method is called after initialization or before destruction.

            The order of the three initializations is:

            Constructor > @PostConstruct > InitializingBean > init-method

      2.3 Aware interface of Bean

    1. Spring provides some interfaces ending with Aware. After the beans that implement the Aware interface are initialized, they can obtain corresponding resources. Such as ApplicationContextAware and BeanNameAware.

            2. Through the Aware interface, you can operate the corresponding Spring resources (be careful).

            3. Provides a convenient entry for simple extension of Spring.

       2.4 Autowiring of Beans

               1. No: Do ​​nothing.

       2, byname: automatic assembly according to the attribute name. This option will check the container and find a bean that matches the property exactly by name, and autowire it with the property.

       3. byType: If there is a bean of the same type as the specified attribute in the container, it will be automatically assembled with the attribute; if there are multiple beans of this type, an exception will be thrown, and it will be pointed out that the byType method cannot be used for automatic assembly; If no matching bean is found, nothing happens.

       4. Constructor: Similar to byType, except that it applies to constructor parameters. If the container does not find a bean of the same type as the constructor parameter, an exception will be thrown.

  2.5 Bean resources

              Unified interface for resource files, including:

             1. UrlResource: The resource corresponding to the URL can be created according to a URL address.

             2. ClassPathResource: Get the resource files under the classpath.

             3. FileSystemResource: Get the resources in the file system.

             4. ServletContextResource: The resources encapsulated by ServletContext are used to access resources in the ServletContext environment.

             5. InputStreamResource: The resource encapsulated for the input stream.

             6. ByteArrayResource: For resources encapsulated by byte arrays.

             If there is no URL, no path, etc., the file will be found according to the path of the applicationContext.

         2.6 Annotation Implementation of Bean Management 

     Starting from Spring 3.0, the Spring JavaConfig project provides many features, including defining beans using java instead of XML, such as @Configuration, @Bean, @Import, @DependsOn, @Component, @Respository, @Service, @Controller, etc.

      @Component is a generic annotation that can be used on any Bean.

      @Respository is usually used to annotate DAO classes, the persistence layer.

      @Service is usually used to annotate the Service class, that is, the service layer.

      @Controller is usually used for Controller classes, i.e. control into (MVC). 

    Spring can automatically detect classes and register beans in the ApplicationContext, requiring <context:component-scan>. As follows, all classes under base-package are automatically registered to applicationContext:

          <context:component-scan base-package="com.mss " >
              Spring can also customize scanning by using filters, excluding those files annotated with @Service, such as:
            <context:component-scan base-package="com.yiibai.customer" >
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Service" />		
	    </context:component-scan>
                  or exclude filenames that contain the phrase DAO, such as:
            <context:component-scan base-package="com.yiibai" >
		<context:exclude-filter type="regex"
			expression="com.yiibai.customer.dao.*DAO.*" />		
	    </context:component-scan>

                 2.7 Bean scope

      Usually the Spring component that is automatically looked up has a singleton scope. If the annotation @Scope is not defined as singleton or prototype, the default is singleton.
       The Spring container can manage the life cycle of beans in the singleton scope. In this scope, Spring can know exactly when a bean is created, initialized, and destroyed. For beans with prototype scope, Spring is only responsible for creating them. When the container creates an instance of the bean, the instance of the bean is handed over to the client's code management. The Spring container will no longer track its life cycle and will not manage those The life cycle of beans configured as prototype scope. The execution of the Bean life cycle in Spring is a very complicated process, and readers can use the methods provided by Spring to customize the Bean creation process. The Spring container does a lot of work before making sure a bean instance is available:

           

               2.8 Autowired annotations

        @Autowired, as the name suggests, is automatic wiring, its function is to eliminate the getter/setter in the code Java code and the property in the bean property. Of course, the getter depends on personal needs. If private properties need to be provided externally, they should be reserved.

       @Autowired is handled by Spring BeanPostProcessor, so you cannot apply these annotations on your own BeanPostProcessor or BeanFactoryPostProcessor types, these types must be loaded via XML or Spring's @Bean annotation.

       When lists and maps are annotated with @Autowired, multiple instances of the class are automatically annotated. Lists can be sorted by @Order, but maps cannot be sorted (because maps are key-value pairs).

2.9 @Qualifier annotation

      In the case of autowiring possibly multiple bean instances by type, Spring's @Qualifier annotation can be used to narrow the scope (or specify unique), or it can be used to specify individual constructor parameters or method parameters. Can also be used to annotate collection type variables.

2.10 Java-based container annotations

       @Bean identifies a method for configuring and initializing a new object managed by the SpringIOC container, similar to the <bean/> of an XML configuration file.

        Any method can be annotated with @Bean in Spring's @Component annotated class (just yes). Usually @Configuration is used.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324745439&siteId=291194637