spring IoC concept

  Most of the enterprise architecture is based on the Spring Framework. Its success comes from the concept, not the technology, it is the most central concept of IoC (Inversion of Control) and AOP (Aspect Oriented Programming), which is the basis for the Spring IoC, AOP and it is an important function, the most typical use undoubtedly database transaction.

Spring Overview

  Spring provides the following strategies:
  • For POJO development potential, providing a lightweight and low-invasive programming, you can extend the functionality through configuration POJO (XML, annotations, etc.), by the concept of dependency injection to extensions recommended by the interface programming, emphasizing the idea of OOD development model, reducing coupling system, improve system scalability and readability.
  • Provide programming section, in particular, the company's core applications - database applications, cut by eliminating the complexity of the previous try ... catch ... finally ... your code so that developers can focus more focused on business development rather than the technology itself, but also to avoid misuse try ... catch ... finally statement.
  • In order to integrate various application frameworks and technologies, Spring provides a template class, you can integrate the various frameworks and technologies through the template, such as support HibernateTemplate Hibernate development, support the development of MyBatis SqlSessionTemplate, support RedisTemplate Redis development, etc., so put all kinds enterprise use of technology integrated into the Spring framework, provides a unified template, making it easier to use a variety of techniques.

Spring IoC Overview

  Inversion of control is a relatively abstract concept, we illustrate. In real life, people use to something, people's basic idea is to find something, like a cup of orange juice, for example, in the days without a drink shop, the most straightforward approach is to buy a juice machine, orange, ready to boiling water. Please note that this is a process that you own "initiative" to create, that is, glass of orange juice needs to take the initiative to create. However, to today, due to the prevalence of drink shop, he has no need to own a squeezed orange juice. Drink orange juice when one appears, the first idea is to find a beverage shop contact information, description of the channel you need, address, contact by telephone, micro-letters, etc., under orders to wait, it would send someone up orange juice . Please note that you did not "take the initiative" to create orange juice, orange juice is a beverage shop is created, rather than you, but also fully meet your requirements.
  In order to better illustrate the abstract description above, we take the initiative and create a passive process created in the form of analog Java code.
  Listing: blenders and juice producer

/ ** 
 * blender 
 * / 
public  class Blender { 

    / ** 
     * was stirred 
     * 
     * @param Water Water description 
     * @param Fruit Fruit Description 
     * @param Sugar Sugar Description 
     * @return Juice
      * / 
    public String Mix (Water String, String Fruit , String sugar) { 
        String juice = "this is a glass of a liquid:" + water + "\ n fruit:" + fruit + "\ n sugar:" + sugar + "\ juice n composition" ;
         return juice; 
    } 

} 

/ ** 
 * juice generator 
 * / 
public  class JuiceMaker {

    Private Blender Blender = null ; // stirrer 
    Private String Water; // aqueous described 
    Private String Fruit; // fruit 
    Private String Sugar; // sugar Description 

    / ** 
     * Juice generated 
     * / 
    public String makeJuice () { 
        Blender = new new Blender ();
         return blender.mix (Water, Fruit, Sugar); 
    } 

    / ** ** *** getters and the setter * / 
}

 

  Passive create an object
  code listing: juice maker and juice description

/ ** 
 * Description juices and juice maker 
 * / 
public  class JuiceMaker2 { 

    Private String beverageShop = null ;
     Private the Source Source = null ; 


    public String makeJuice () { 
        String of fileEncoding = the System.getProperty ( "the file.encoding"); // View the system default encoding 
        System.out.println ( "fileEncoding:" + fileEncoding); 
        String Juice = "this is caused by" + beverageShop + "beverage shop, provided" + source.getSize () + source.getSugar ( ) + source.getFruit ();
         return Juice; 
    } 


    / ** ** *** getters and the setter * /
} 

Public  class the Source { 

    Private String Fruit; // Type 
    Private String Sugar; // sugar described 
    Private Integer size; // cup size 

    / ** ** *** getters and the setter * / 
}

 

Spring IoC explained

  With the above example, let's illustrate the concept of Inversion of Control: Inversion of Control is a way to generate and acquire a particular object or through a third party by describing (in Java can be XML or annotations) are.
  Achieve control is inverted in Spring IoC container, which implementation is dependent injection (Dependency Injection, DI). As the above example, fruit juice drinks manufacturing relies on the shop and orders to manufacture juices, and others to create a beverage shop, we only need to know that it can produce fruit juice can, and do not need to understand how to create a juice.

Spring IoC container

  The role of the Spring IoC container, which can accommodate a variety of Bean we have developed, and we can derive various published in Spring IoC container of Bean, and you can get it by description.

Design Spring IoC container

  Spring IoC container design is mainly based on two BeanFactory and ApplicationContext interfaces, sub-interfaces is one wherein ApplicationContext BeanFactory, in other words the lowest level of the interface BeanFactory Spring IoC container as defined, and is one of its senior Interface ApplicationContext and functions of BeanFactory done a lot of useful extensions, so in most of the scenes work, will use ApplicationContext as the Spring IoC container
Listing: spring-cfg.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-4.0.xsd">

    <bean id="source" class="com.ssm.chapter9.pojo.Source">
        <property name="fruit" value="橙汁"/>
        <property name="sugar" value="少糖"/>
        <property name="size" value="3"/>
    </bean>

    <bean id="juiceMaker2" class="com.ssm.chapter9.pojo.JuiceMaker2">
        <property name="beverageShop" value="贡茶"/>
        <property name="source" ref="source"/>
    </bean>

</beans>
ApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter9/spring-cfg.xml");
JuiceMaker2 juiceMaker2 = (JuiceMaker2) ctx.getBean("juiceMaker2");
System.out.println(juiceMaker2.makeJuice());

 

Initialization and dependency injection Spring IoC container

  It should be noted that Bean initialization and dependency injection in Spring IoC container are two main steps, it is after initialization, will perform dependency injection. Bean initialization is divided into three steps:
(1) Resource positioning, this step is the Spring IoC container configuration according to developers, locate resources in the development of Spring by XML or annotations are very common ways of positioning content It is provided by the developer.
(2) BeanDefinition loading, this process is corresponding to POJO Spring acquired according to the configuration of the developer, to generate the corresponding process instance.
(. 3) BeanDefinition registration, this is equivalent to step through before loading BeanDefinition POJO Spring IoC container into registration, so that it can develop and test personnel can gain Bean Spring IoC container by description.
  Done these three steps, Bean get in the Spring IoC container initialization, but did not complete dependency injection, that is not configured to inject resources Bean, then it can not fully use. For dependency injection, Spring Bean as well as a configuration option --lazy-init, its meaning is whether to initialize Spring Bean. In the absence of any configuration circumstances, it defaults to default, the actual value is false, that is, by default, automatically initialized Spring IoC Bean. If set to true, then only when we use Spring IoC container getBean method to get it, it will be initialized, complete dependency injection.

Spring Bean Life Cycle

  SpringIoC essential purpose is to manage the container Bean. For Bean, the presence of its life cycle in the container, its initialization and destruction also requires a process, in some processes need to customize, we can insert code to change some of their behavior to meet specific needs, which We need to use the knowledge of the life cycle of a Spring Bean.
  Mainly to understand the life cycle of the Spring IoC container and initialization process of destruction Bean, through its learning method we can know how to join in custom initialization and when destroyed, in order to meet specific needs.
  BeanPostProcessor interface is for all Bean terms; the interface is DisposableBean for Spring IoC container itself. When a Bean implements the above interface, we only need to define it may in the Spring IoC container, Spring IoC container will automatically recognize.
  Listing: BeanPostProcessor implementation class

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl implements BeanPostProcessor {

    // @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("【" + bean.getClass().getSimpleName() + "】对象" + beanName + "开始实例化");
        return bean;
    }

    // @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws{BeansException 
        System.out.println ( "[". + Bean.getClass () getSimpleName ( ) + " Object]" + beanName + "have instantiated" );
         return the bean; 
    } 
}

 

  Listing: DisposableBean implementation class

import org.springframework.beans.factory.DisposableBean;

public class DisposableBeanImpl implements DisposableBean {

    // @Override
    public void destroy() throws Exception {
        System.out.println("调用接口DisposableBean的destroy方法");
    }

}


  Listing: JuiceMaker2_1

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class JuiceMaker2_1 implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean {

    private String beverageShop = null;
    Private the Source Source = null ; 


    public  void the init () { 
        System.out.println ( "[" + the this . .getClass () getSimpleName () + 
                "] perform custom initialization method" ); 
    } 

    public  void the destroy () { 
        the System .out.println ( "[" + the this .getClass () getSimpleName () +. "] perform a custom destruction method" ); 
    } 

    public String makeJuice () { 
        String Juice = "this is a cup by the" + beverageShop + "drinks shop, provided "+ source.getSize () + source.getSugar () + source.getFruit ();
         return Juice;
    }

    // @Override
    public void setBeanName(String arg0) {
        System.out.println("【" + this.getClass().getSimpleName() + "】调用BeanNameAware接口的setBeanName方法");
    }

    // @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        System.out.println("【" + this.getClass().getSimpleName() + "】调用BeanFactoryAware接口的setBeanFactory方法");
    }

    // @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        System.out.println("【" + this.getClass().getSimpleName() + "】调用ApplicationContextAware接口的setApplicationContext方法");
    }

    // @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("【" + this.getClass().getSimpleName() + "】调用InitializingBean接口的afterPropertiesSet方法");
    }

    /**** setter and getter ****/
}

 

  Listing: custom declaration and initialization methods of destruction Bean spring-cfg2.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-4.0.xsd">

    <!--BeanPostProcessor定义-->
    <bean id="beanPostProcessor" class="com.ssm.chapter9.bean.BeanPostProcessorImpl"/>  <!--DisposableBean定义 -->
    <bean id="disposableBean" class="com.ssm.chapter9.bean.DisposableBeanImpl"/>
    <bean id="source" class="com.ssm.chapter9.pojo.Source">
        <property name="fruit" value="橙汁"/>
        <property name="sugar" value="少糖"/>
        <property name="size" value="3"/>
    </bean>

    <bean id="juiceMaker2_1" class="com.ssm.chapter9.pojo.JuiceMaker2_1" init-method="init" destroy-method="destroy">
        <property name="beverageShop" value="贡茶"/>
        <property name="source" ref="source"/>
    </bean>

</beans>

 

  Listing: Testing Spring Bean Life Cycle

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter9/spring-cfg2.xml");
JuiceMaker2_1 juiceMaker2_1 = (JuiceMaker2_1) ctx.getBean("juiceMaker2_1");
System.out.println(juiceMaker2_1.makeJuice());
ctx.close();

 

summary

  Emphasis on understanding the use of basic design benefits of Spring IoC and its container, to understand the Spring IoC container primarily to manage Bean and services, need to pay attention to grasp the most basic method of BeanFactory defined, as well as the use of Spring Bean life cycle, by those life cycle interfaces and methods that allow us to customize initialization and destruction methods.

 

Reference: SSM framework of Chapter IX

Guess you like

Origin www.cnblogs.com/ooo0/p/10962330.html