IOC design in Spring
The IOC module in Spring can be divided into three roles, corresponding to three top-level interfaces respectively:
Popular understanding:
- BeanDefinition: a Bean is a book.
- BeanDefinitionRegistry: a bookcase where books are stored.
- -Leonard: Well, the BeanFactory is a library.
In our implementation, we also use these three concepts. Let’s take a look at the methods for the three interfaces:
BeanDefinition
public interface BeanDefinition {
// 0: not initialized
int STATUS_UNINITIALIZED = 0;
// 1 indicates initialization
int STATUS_INITIALIZED = 1;
/**
* Sets name.
*
* @param beanClassName the bean class name
*/
void setName(String beanClassName);
/**
* Gets name.
*
* @return the name
*/
String getName(a);
/**
* Sets instance.
*
* @param instance the instance
*/
void setInstance(Object instance);
/**
* Gets instance.
*
* @return the instance
*/
Object getInstance(a);
/**
* Gets bean class.
*
* @return bean class
*/Class<? > getBeanClass();/** * Determines whether the bean has been initialized@return status == {@link#STATUS_INITIALIZED} ? * /
Boolean isInit(a);
/**
* set status to {@link #STATUS_INITIALIZED}
*/
void setStatusInitialized(a);
}
Copy the code
BeanDefinitionRegistry
public interface BeanDefinitionRegistry {
/** * Register a new Bean **@paramBeanName beans are registered using the name *@paramThe type of beanDefinition bean */
void registerBean(String beanName, BeanDefinition beanDefinition);
/** * remove a Bean **@paramBeanName Specifies the name of the Bean to remove */
void removeBean(String beanName);
/** * get Bean ** by name@paramBeanName bean name *@returnRegistered {@linkBeanDefinition} * / object
BeanDefinition getBean(String beanName);
/** * get Bean * {@link BeanDefinition}
*
* @paramBeanName bean name *@paramRequiredType Bean type, which validates *@returnRegistered {@linkBeanDefinition} * / object
<T> BeanDefinition getBean(String beanName, Class<T> requiredType);
}
Copy the code
BeanFactory
public interface BeanFactory {
/** * get bean ** by name@paramBeanName bean name *@returnThe bean name corresponds to the bean */
BeanDefinition getBeanInstance(String beanName);
/** * get a bean by name **@paramThe name of the beanName bean@paramRequiredType Bean type *@returnThe bean name corresponds to the bean */
<T> T getBeanInstance(String beanName, Class<T> requiredType);
}
Copy the code
Our IOC class diagram
The default implementation classes have been added to each of the three top-level interfaces, with some important points:
- BeanDefinitionRegistry uses a Map for storing beans, with Key being the Bean name and Val being BeanDefinition
- There are three fields in BeanDefinition
private String beanName; / / the name of the bean private T beanInstance = null; // An instance of the bean private final Class<T> beanClass; // The class of the bean Copy the code
- BeanFactory stores the BeanDefinitionRegistry class, which encapsulates the interface to get beans, and is provided externally by the factory