(Spring-10th (IoC basics) InstantiationStrategy-the third major tool for instantiating Bean, instantiation
The entire Bean instantiation process is as follows:
:
Specifically, after BeanDefinition is added to the Registry and processed by the BeanFactoryPostProcessor implementation class, InstantiationStrategy is responsible for instantiation. Instantiation is just to call the constructor, which is equivalent to a new object. The specific attributes of bean are not assigned a value at this time (of course, the Bean attribute value is configured in XML at the beginning, or if there is a value assignment statement in the constructor, the relevant attribute will have a value during instantiation .). InstantiationStrategy is responsible for instantiating beans by default constructor of Bean classes, constructor with parameters, or factory methods. Instantiation
The inheritance structure of Strategy (note that the following is the parent class, the top is the subclass, the solid line is the inheritance, and the dotted line is the implementation ):
InstantiationStrategy is just a strategic interface.
SimpleInstantiationStrategy is the implementation class of InstantiationStrategy. This class is a simple class used for Bean instantiation. For example, Bean is instantiated By Default constructors of Bean classes, constructors with parameters, or factory methods. It can be seen that this class has an instantiationWithMethodInjection method, but in fact this is only a hook, and does not really support method injection.
Method injection: In most cases, the beans in the container are of the singleton type (default). The singleton type means that spring will only instantiate the bean once and put the bean in the buffer pool, return the bean reference (Address) to the caller. If a singleton bean references another singleton bean or a prototype bean references another prototype bean, generally, you can define a bean as the property value of another bean. As shown below:
<bean id="boss" class="com.baobaotao.attr.Boss"> <property name="car"> <ref parent="car" /> </property> </bean>
However, this may cause problems for beans with different lifecycles. For example, when calling A method of A singleton bean, bean B that needs to reference another prototype type (bean will be re-instantiated every call). For bean A, the container will only be created once, in this way, the container cannot provide A new bean B instance for bean A every time when necessary. That is to say, each time I call A, I need A re-instantiated B. Because A will only be instantiated once and B will be instantiated with the instantiation of A, the B I get is not instantiated again. In this case, use method injection. For example:
1 <bean id = "car" class = "com. baobaotao. injectfun. car "2 p: brand =" caca72 "p: price =" 2000 "scope =" prototype "/> 3 4 <bean id =" magicBoss "class =" com. baobaotao. injectfun. magicBoss "> 5 <lookup-method name =" getCar "bean =" car "/> 6 </bean>
Use the lookup-method label. In this way, the getCar method is loaded every time magicBoss is instantiated, as follows:
public interface MagicBoss { Car getCar(); }
Because bean = "car" is defined in lookup-method, spring will automatically instantiate the car. It is equivalent to writing a method to instantiate a car in getCar.
The inherited class of SimpleInstantiationStrategy is CglibSubclassingInstantiationStrategy. It inherits SimpleInstantiationStrategy and overwrites the instantiationWithMethodInjection method. However, you must use the cglib class library to use this method. It uses cglib to dynamically generate a subclass for bean. This class is called a proxy class. It generates the method injection logic in the subclass and then uses this dynamically generated subclass to create bean instances. (For more information about this technology, see spring's AOP for Aspect-Oriented Programming. ).
Next, let's take a look at the default instantiate method of SimpleInstantiationStrategy:
1 public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { 2 // Don't override the class with CGLIB if no overrides. 3 if (beanDefinition.getMethodOverrides().isEmpty()) { 4 Constructor<?> constructorToUse; 5 synchronized (beanDefinition.constructorArgumentLock) { 6 constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; 7 if (constructorToUse == null) { 8 final Class clazz = beanDefinition.getBeanClass(); 9 if (clazz.isInterface()) {10 throw new BeanInstantiationException(clazz, "Specified class is an interface");11 }12 try {13 if (System.getSecurityManager() != null) {14 constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() {15 public Constructor run() throws Exception {16 return clazz.getDeclaredConstructor((Class[]) null);17 }18 });19 }20 else {21 constructorToUse = clazz.getDeclaredConstructor((Class[]) null);22 }23 beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;24 }25 catch (Exception ex) {26 throw new BeanInstantiationException(clazz, "No default constructor found", ex);27 }28 }29 }30 return BeanUtils.instantiateClass(constructorToUse);31 }32 else {33 // Must generate CGLIB subclass.34 return instantiateWithMethodInjection(beanDefinition, beanName, owner);35 }36 }
Since the source code will not be discussed too much in the previous post, I just want to know about it. From lines 7th and 21st, we can see that if the bean does not have its own constructor, then, the reflection mechanism is used to call the default no-argument constructor to instantiate the bean. In the last 30 rows, get the constructor and execute the BeanUtils. instantiateClass method. The method is as follows:
1 public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException { 2 Assert.notNull(ctor, "Constructor must not be null"); 3 try { 4 ReflectionUtils.makeAccessible(ctor); 5 return ctor.newInstance(args); 6 } 7 catch (InstantiationException ex) { 8 throw new BeanInstantiationException(ctor.getDeclaringClass(), 9 "Is it an abstract class?", ex);10 }11 catch (IllegalAccessException ex) {12 throw new BeanInstantiationException(ctor.getDeclaringClass(),13 "Is the constructor accessible?", ex);14 }15 catch (IllegalArgumentException ex) {16 throw new BeanInstantiationException(ctor.getDeclaringClass(),17 "Illegal arguments for constructor", ex);18 }19 catch (InvocationTargetException ex) {20 throw new BeanInstantiationException(ctor.getDeclaringClass(),21 "Constructor threw exception", ex.getTargetException());22 }23 }
Line 4 and line 5 are used to create an instance (first, set the constructed function to accessible ).
The bean instantiated by InstantiationStrategy is equivalent to generating a new object. The specific attribute assignment must be completed by BeanWrapper in combination with the Attribute Editor. BeanWrapper and Attribute Editor will be detailed in the following blog.
Learn but do not know, and do not learn the same; do not know, and do not know the same.
-- Huang Yu