Several problems and principles of springbean

Time:2020-11-25

1、 Several questions

  1. How to generate beans in spring?
  2. What extension points does spring provide to integrate third-party frameworks
  3. How spring integrates mybatis

2、 What is spring

Spring manages beans (objects in Java), initializes operations,

3、 Spring IOC container

  1. Resource components:

    Resource refers to the description of resource files. Different resource files, such as XML and properties files, have different formats, and will eventually be loaded by resourceloader to obtain the corresponding resource object. Master configuration file. The master configuration serves as the entry point for all configurations

  2. Resource loading component:

    Resourceloader: loads XML, properties and other format files, parses files, and generates resource objects. What resolved configuration resources are loaded

  3. Bean container component:

    Beanfactory architecture: the core of the IOC container, for which other components work (but not just for it)

  4. Bean registration component:

    Singletonbeanregister / aliasregister: register the beandefinition object in beanfactory (beandefinition map). The container used to register the object

  5. Bean description component:

    Beandefinition system, the basic data structure described by spring for bean. Responsible for describing the beandefinition resource, transforming the bean in the form of resource into the format structure expected by spring

  6. Bean construction component:

    Beandefinitionreader system, read resources and convert their data into beandefinition objects. Be responsible for transforming the resource resolution into beandefinition to prepare for describing beans later

<img style=”zoom:50%;float:left” />

4、 Beanfactory

4.1 preparation
  • bean-v1.xmlto configurebeanInformation for
  • BeanDefinitionFor storagebeanDefinition of
  • BeanFactoryGet beanInformation, instantiationbean`
  • BeanFactoryTesttestBeanFactoryIs it available
4.2 code implementation
  1. bean-v1.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans>
        <bean id="user" class="com.timwang.spring.small.User"/>
        <bean id="invalidBean" class="xxx.xxx"/>
    </beans>    
  2. BeanDefinition

    bean-v1.xmlEach is defined inbeanBut how do we store this information?springYesBeanDefinitionInterfacebeanDefinition of

    package com.timwang.spring.small;
    
    /**
     * @author wangjun
*/

public interface BeanDefinition {

/**
    *Get bean.xml The full name of the bean in the“ com.niocoder.service .v1.NioCoderService"
    * @return string
    */
   String getBeanClassName();

}

`Genericbeandefinition 'implements the' beandefinition 'interface

package com.timwang.spring.small;

/**

* @author wangjun
* @date 2020-06-29
*/

public class GenericBeanDefinition implements BeanDefinition {

   private String id;
   private String beanClassName;

   public GenericBeanDefinition(String id, String beanClassName) {
       this.id = id;
       this.beanClassName = beanClassName;
   }

   @Override
   public String getBeanClassName() {
       return this.beanClassName;
   }

   public String getId() {
       return id;
   }

}

3. BeanFactory

We have used 'beandefinition' to describe the definition of 'bean' in 'bean-v1. XML'. Next, we use 'beanfactory' to obtain an instance of 'bean'

package com.timwang.spring.small;

/**

*Create an instance of a bean
* @author wangjun
* @date 2020-06-29
*/

public interface BeanFactory {

/**
    *Get the definition of the bean
    * @param beanId beanId
    * @return BeanDefinition
    */
   BeanDefinition getBeanDefinition(String beanId);

   /**
    *Get an instance of the bean
    * @param beanId beanId
    *Return @ bean
    */
   Object getBean(String beanId);

}

`Defaultbeanfactory 'implements the' beanfactory 'interface

package com.timwang.spring.small;

import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.util.ClassUtils;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.dom4j.io.SAXReader;

/**

*Default implementation class of beanfactory
*
* @author wangjun
* @date 2020-06-29
*/

public class DefaultBeanFactory implements BeanFactory {

private static final String ID_ATTRIBUTE = "id";
   private static final String CLASS_ATTRIBUTE = "class";
   /**
    *Storing beandefinition
    */
   private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

   public DefaultBeanFactory(String configFile) {
       loadBeanDefinition(configFile);
   }

   @Override
   public BeanDefinition getBeanDefinition(String beanId) {
       return beanDefinitionMap.get(beanId);
   }

   @Override
   public Object getBean(String beanId) {
       BeanDefinition bd = this.getBeanDefinition(beanId);
       if (bd == null) {
           throw new BeanCreationException("BeanDefinition does not exist");
       }
       ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
       String beanClassName =  bd.getBeanClassName();
       try {
           //Using reflection to create an instance of a bean requires a default nonparametric construction method for the object
           Class<?> aClass = classLoader.loadClass(beanClassName);
           return aClass.newInstance();
       } catch (Exception e) {
           throw new BeanCreationException("Bean Definition does not exist");
       }
   }

   /**
    *Specific analysis bean.xml Using Dom4j
    * @param configFile configFile
    */
   private void loadBeanDefinition(String configFile) {
       ClassLoader cl = ClassUtils.getDefaultClassLoader();
       try (InputStream is = cl.getResourceAsStream(configFile)) {
           SAXReader reader = new SAXReader();
           Document doc = reader.read(is);

           Element root = doc.getRootElement();
           Iterator elementIterator = root.elementIterator();
           while (elementIterator.hasNext()) {
               Element ele = (Element) elementIterator.next();
               String id = ele.attributeValue(ID_ATTRIBUTE);
               String beanClassName = ele.attributeValue(CLASS_ATTRIBUTE);
               BeanDefinition bd = new GenericBeanDefinition(id, beanClassName);
               this.beanDefinitionMap.put(id, bd);
           }
       } catch (Exception e) {
           throw new BeanDefinitionStoreException("IOException parsing XML document", e);
       }
   }

}


4. BeanFactoryTest

package com.timwang.spring.small;

/**

* @author wangjun
* @date 2020-06-29
*/

public class BeanFactoryTest {

   public static void main(String[] args) {
       BeanFactoryTest beanFactoryTest = new BeanFactoryTest();
       beanFactoryTest.testGetBean();
   }

   public void testGetBean() {
       BeanFactory beanFactory = new DefaultBeanFactory("bean-v1.xml");
       BeanDefinition bd = beanFactory.getBeanDefinition("user");
       String beanClassName = bd.getBeanClassName();
       System.out.println(beanClassName);
   }

}