In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of Spring initializing Bean instance object in this way. The content is detailed and easy to understand, easy to operate, and has certain reference value. I believe everyone will gain something after reading this article on initializing Bean instance object in Spring. Let's take a look at it.
Code entry
PreInstantiateSingletons method of DefaultListableBeanFactory
DefaultListableBeanFactory's preInstantiateSingletons method, as its name implies, initializes all singleton Bean. Take a look at the definition of the method:
Public void preInstantiateSingletons () throws BeansException {
If (this.logger.isInfoEnabled ()) {
This.logger.info ("Pre-instantiating singletons in" + this)
}
Synchronized (this.beanDefinitionMap) {
/ / Iterate over a copy to allow for init methods which in turn register new bean definitions.
/ / While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List beanNames = new ArrayList (this.beanDefinitionNames)
For (String beanName: beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition (beanName)
If (! bd.isAbstract () & & bd.isSingleton () & &! bd.isLazyInit ()) {
If (isFactoryBean (beanName)) {
Final FactoryBean factory = (FactoryBean) getBean (FACTORY_BEAN_PREFIX + beanName)
Boolean isEagerInit
If (System.getSecurityManager ()! = null & & factory instanceof SmartFactoryBean) {
IsEagerInit = AccessController.doPrivileged (new PrivilegedAction () {
Public Boolean run () {
Return (SmartFactoryBean) factory. IsEagerInit ()
}
}, getAccessControlContext ()
}
Else {
IsEagerInit = (factory instanceof SmartFactoryBean & &
((SmartFactoryBean) factory) .isEagerInit ()
}
If (isEagerInit) {
GetBean (beanName)
}
}
Else {
GetBean (beanName)
}
}
}
}
}
The previous code is relatively simple, getting BeanDefinition (that is, the definition of Bean) according to beanName. Because this method instantiates all non-lazily loaded singleton Bean, to instantiate Bean, you must meet the three definitions of 11 lines:
(1) not abstract
(2) it must be a single case.
(3) must be non-lazy loading
Then take a brief look at lines 12-29 of the code, this code is mainly to do one thing: first determine whether Bean is the implementation of FactoryBean, and then determine whether Bean is the implementation of SmartFactoryBean, if Bean is the implementation of SmartFactoryBean and eagerInit (the word literally means eager to load, can not find a good word to translate, meaning to define the meaning that the Bean needs to be loaded immediately), the Bean will be instanced immediately. Java developers don't need to pay attention to this code, because SmartFactoryBean is basically not used. I'll translate the definition description of SmartFactoryBean on Spring's official website:
The extended interface of the FactoryBean interface. The interface implementation does not indicate whether a separate instance object is always returned. For example, if the FactoryBean.isSingleton () implementation returns false, it does not clearly indicate that each time it returns a separate instance object.
Instead of implementing a simple FactoryBean implementation of this extension interface, the FactoryBean.isSingleton () implementation returns false simply telling us that each time we return a separate instance object, and that the exposed object can only be accessed through a command
Note: this interface is a special-purpose interface, mainly used within the framework for use related to Spring. In general, the implementation of the FactoryBean interface provided by the application should only need to implement a simple FactoryBean interface, and the new method should be added to the extended interface
Code example
For the convenience of later code analysis, I define a Bean in advance:
Package org.xrq.action
Import org.springframework.beans.factory.BeanClassLoaderAware
Import org.springframework.beans.factory.BeanNameAware
Import org.springframework.beans.factory.InitializingBean
Public class MultiFunctionBean implements InitializingBean, BeanNameAware, BeanClassLoaderAware {
Private int propertyA
Private int propertyB
Public int getPropertyA () {
Return propertyA
}
Public void setPropertyA (int propertyA) {
This.propertyA = propertyA
}
Public int getPropertyB () {
Return propertyB
}
Public void setPropertyB (int propertyB) {
This.propertyB = propertyB
}
Public void initMethod () {
System.out.println ("Enter MultiFunctionBean.initMethod ()")
}
@ Override
Public void setBeanClassLoader (ClassLoader classLoader) {
System.out.println ("Enter MultiFunctionBean.setBeanClassLoader (ClassLoader classLoader)")
}
@ Override
Public void setBeanName (String name) {
System.out.println ("Enter MultiFunctionBean.setBeanName (String name)")
}
@ Override
Public void afterPropertiesSet () throws Exception {
System.out.println ("Enter MultiFunctionBean.afterPropertiesSet ()")
}
@ Override
Public String toString () {
Return "MultiFunctionBean [propertyA=" + propertyA + ", propertyB=" + propertyB + "]"
}
}
Define the corresponding spring.xml:
With this MultiFunctionBean, we can use it to explore the various mechanisms by which Spring loads Bean.
DoGetBean method to construct Bean process
The above analysis of all the code outside getBean, you can see that the Bean object instance is obtained through the getBean method, and the getBean method finally calls the doGetBean method of DefaultListableBeanFactory's parent class AbstractBeanFactory class, so this part focuses on analyzing how the doGetBean method constructs a singleton Bean.
Take a look at the code implementation of the doGetBean method, which is longer:
Protected T doGetBean (
Final String name, final Class requiredType, final Object [] args, boolean typeCheckOnly)
Throws BeansException {
Final String beanName = transformedBeanName (name)
Object bean
/ / Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton (beanName)
If (sharedInstance! = null & & args = = null) {
If (logger.isDebugEnabled ()) {
If (isSingletonCurrentlyInCreation (beanName)) {
Logger.debug ("Returning eagerly cached instance of singleton bean'" + beanName +
"'that is not fully initialized yet-a consequence of a circular reference")
}
Else {
Logger.debug ("Returning cached instance of singleton bean'" + beanName + "'")
}
}
Bean = getObjectForBeanInstance (sharedInstance, name, beanName, null)
}
Else {
/ / Fail if we're already creating this bean instance:
/ / We're assumably within a circular reference.
If (isPrototypeCurrentlyInCreation (beanName)) {
Throw new BeanCurrentlyInCreationException (beanName)
}
/ / Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory ()
If (parentBeanFactory! = null & &! containsBeanDefinition (beanName)) {
/ / Not found-> check parent.
String nameToLookup = originalBeanName (name)
If (args! = null) {
/ / Delegation to parent with explicit args.
Return (T) parentBeanFactory.getBean (nameToLookup, args)
}
Else {
/ / No args-> delegate to standard getBean method.
Return parentBeanFactory.getBean (nameToLookup, requiredType)
}
}
If (! typeCheckOnly) {
MarkBeanAsCreated (beanName)
}
Final RootBeanDefinition mbd = getMergedLocalBeanDefinition (beanName)
CheckMergedBeanDefinition (mbd, beanName, args)
/ / Guarantee initialization of beans that the current bean depends on.
String [] dependsOn = mbd.getDependsOn ()
If (dependsOn! = null) {
For (String dependsOnBean: dependsOn) {
GetBean (dependsOnBean)
RegisterDependentBean (dependsOnBean, beanName)
}
}
/ / Create bean instance.
If (mbd.isSingleton ()) {
SharedInstance = getSingleton (beanName, new ObjectFactory () {
Public Object getObject () throws BeansException {
Try {
Return createBean (beanName, mbd, args)
}
Catch (BeansException ex) {
/ / Explicitly remove instance from singleton cache: It might have been put there
/ / eagerly by the creation process, to allow for circular reference resolution.
/ / Also remove any beans that received a temporary reference to the bean.
DestroySingleton (beanName)
Throw ex
}
}
});
Bean = getObjectForBeanInstance (sharedInstance, name, beanName, mbd)
}
Else if (mbd.isPrototype ()) {
/ / It's a prototype-> create a new instance.
Object prototypeInstance = null
Try {
BeforePrototypeCreation (beanName)
PrototypeInstance = createBean (beanName, mbd, args)
}
Finally {
AfterPrototypeCreation (beanName)
}
Bean = getObjectForBeanInstance (prototypeInstance, name, beanName, mbd)
}
Else {
String scopeName = mbd.getScope ()
Final Scope scope = this.scopes.get (scopeName)
If (scope = = null) {
Throw new IllegalStateException ("No Scope registered for scope'" + scopeName + "'")
}
Try {
Object scopedInstance = scope.get (beanName, new ObjectFactory () {
Public Object getObject () throws BeansException {
BeforePrototypeCreation (beanName)
Try {
Return createBean (beanName, mbd, args)
}
Finally {
AfterPrototypeCreation (beanName)
}
}
});
Bean = getObjectForBeanInstance (scopedInstance, name, beanName, mbd)
}
Catch (IllegalStateException ex) {
Throw new BeanCreationException (beanName
"Scope'" + scopeName + "'is not active for the current thread;" +
"consider defining a scoped proxy for this bean if you intend to refer to it from a singleton"
Ex)
}
}
}
/ / Check if required type matches the type of the actual bean instance.
If (requiredType! = null & & bean! = null & &! requiredType.isAssignableFrom (bean.getClass () {
Try {
Return getTypeConverter () .convertIfNecessary (bean requiredType)
}
Catch (TypeMismatchException ex) {
If (logger.isDebugEnabled ()) {
Logger.debug ("Failed to convert bean'" + name + "'to required type [" +
ClassUtils.getQualifiedName (requiredType) + "]", ex)
}
Throw new BeanNotOfRequiredTypeException (name, requiredType, bean.getClass ())
}
}
Return (T) bean
}
This is the end of the article on "how Spring initializes Bean instance objects". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "Spring initializes Bean instance objects". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.