In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to configure Spring containers". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to configure Spring containers".
1. Overview of containers
We can roughly divide the Ioc containers in Spring into two types:
BeanFactoryApplicationContext1.1 BeanFactory
BeanFactory is the most basic IoC container, which provides the basic functionality required by an IoC container. The XmlBeanFactory we used in the previous articles in this series is one of its implementations.
BeanFactory adopts delayed initialization policy by default, that is, when the container starts, the initialization of Bean is not completed. Only when the instance of the Bean is called, the initialization operation will be completed and dependency injection will be carried out.
For example, the following code:
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource ("beans.xml"))
User user = factory.getBean (User.class)
The User object configured in beans.xml is not initialized when the first line of code is executed, and the User object is initialized only when the second line of getBean method is called.
The advantage of this design is that the container starts quickly because there is less work to be done.
1.2 ApplicationContext
ApplicationContext is implemented on the basis of BeanFactory, and it has all the functions of BeanFactory, which can be regarded as an advanced container.
ApplicationContext provides event publishing, internationalization and other functions on the basis of BeanFactory.
At the same time, there is a big difference between ApplicationContext and BeanFactory in that ApplicationContext initializes all Bean when the container starts, which means that the container takes a long time to start and requires higher system resources.
For example, the following code:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext ("beans.xml")
When this code is executed, the User object configured in beans.xml completes the initialization operation.
2.BeanFactory
BeanFactory's inheritance diagram is too large to be fully displayed in the article. Friends can check it on their own in IDEA, so I won't post it here.
Let's take a look at the BeanFactory source code:
Public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&"
Object getBean (String name) throws BeansException
T getBean (String name, Class requiredType) throws BeansException
Object getBean (String name, Object... Args) throws BeansException
T getBean (Class requiredType) throws BeansException
T getBean (Class requiredType, Object...) Args) throws BeansException
ObjectProvider getBeanProvider (Class requiredType)
ObjectProvider getBeanProvider (ResolvableType requiredType)
Boolean containsBean (String name)
Boolean isSingleton (String name) throws NoSuchBeanDefinitionException
Boolean isPrototype (String name) throws NoSuchBeanDefinitionException
Boolean isTypeMatch (String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException
Boolean isTypeMatch (String name, Class typeToMatch) throws NoSuchBeanDefinitionException
@ Nullable
Class getType (String name) throws NoSuchBeanDefinitionException
@ Nullable
Class getType (String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException
String [] getAliases (String name)
}
As you can see, BeanFactory mainly provides some query methods related to Bean.
FACTORY_BEAN_PREFIX
This is the defined FactoryBean prefix. For more information, please refer to the Spring source code section 9 for an in-depth analysis of FactoryBean.
GetBean
There are five getBean methods.
When you get a Bean, you can specify the name of the Bean, the type of Bean, or at the same time, which is easy to understand.
There are also two overloaded methods that contain an args parameter, which may not be used by some friends. I'll explain it a little bit here.
In fact, we can probably guess that args is the parameter needed to obtain Bean. If you use this method to configure parameters for Bean, you need to set the scope of Bean to prototype, which means that Bean is initialized every time you get Bean (otherwise the configured parameters cannot take effect).
Brother Song uses an example to show you.
First, we provide a User class:
Public class User {
Private String username
Private Integer age
Public User (String username, Integer age) {
This.username = username
This.age = age
}
Public String getUsername () {
Return username
}
Public void setUsername (String username) {
This.username = username
}
Public Integer getAge () {
Return age
}
Public void setAge (Integer age) {
This.age = age
}
@ Override
Public String toString () {
Return "User {" +
"username='" + username +'\'+
", age=" + age +
'}'
}
}
As you can see, the User class has only one constructor with parameters.
Next we configure it in the XML file, where we need to configure the constructor parameter of the User class, which we can configure to null, and remember to set the scope property to prototype.
Finally, load the Bean as follows:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext ("beans.xml")
User user = ctx.getBean (User.class,new Object [] {"javaboy", 99})
System.out.println ("user =" + user)
The final print result is as follows:
User = User {username='javaboy', age=99}
As you can see, the parameters configured for Bean are in effect.
GetBeanProvider
Method is used to get the provider of the specified Bean, and you can see that it returns an ObjectProvider, which extends from ObjectFactory and is provided from Spring4.3.
Maybe you have less contact with ObjectProvider, so let me talk a little bit about it here.
Let's first take a look at ObjectFactory:
@ FunctionalInterface
Public interface ObjectFactory {
T getObject () throws BeansException
}
ObjectFactory is a bit similar to the FactoryBean we talked about in the article FactoryBean, which is similar to the ninth article of the Spring source code.
The difference is that there is only one getObject method in ObjectFactory, which returns an instance of Object. ObjectFactory is similar to FactoryBean, but the implementation of the latter is usually defined as a SPI instance in BeanFactory, while such implementations are usually injected into other Bean as API.
Let's take a look at ObjectProvider (part):
Public interface ObjectProvider extends ObjectFactory, Iterable {
/ / returns a bean of the specified type. If it does not exist in the container, a NoSuchBeanDefinitionException exception is thrown. If there are multiple bean of this type in the container, a NoUniqueBeanDefinitionException exception is thrown.
T getObject (Object... Args) throws BeansException
/ / return bean instance if the specified type of bean is registered in the container, otherwise return null
@ Nullable
T getIfAvailable () throws BeansException
/ / if the specified type of bean has only one bean in the container, return bean instance, if it does not exist, return null;. If there are multiple bean of this type in the container, throw a NoUniqueBeanDefinitionException exception.
@ Nullable
T getIfUnique () throws BeansException
Provided after / / Spring5.0, returns the iterator of the specified type Bean
@ Override
Default Iterator iterator () {
Return stream () .iterator ()
}
/ / convert to Stream
Default Stream stream () {
Throw new UnsupportedOperationException ("Multi element access not supported")
}
Default Stream orderedStream () {
Throw new UnsupportedOperationException ("Ordered element access not supported")
}
}
This is the source code of ObjectProvider, so what's the use of it? Brother Song, give me a simple example.
Before Spring4.3.
Suppose I have a UserDao, as follows:
@ Repository
Public class UserDao {
}
There is also a UserService, as follows:
@ Service
Public class UserService {
Private UserDao userDao
@ Autowired
Public UserService (UserDao userDao) {
This.userDao = userDao
}
@ Override
Public String toString () {
Return "UserService {" +
"userDao=" + userDao +
'}'
}
}
When injecting UserDao into UserService, the @ Autowired annotation must be explicitly given.
It doesn't look elegant enough!
Starting with Spring4.3, when injecting UserDao into UserService, if the constructor has only one parameter, you don't have to add the @ Autowired annotation, like this:
@ Service
Public class UserService {
Private UserDao userDao
Public UserService (UserDao userDao) {
This.userDao = userDao
}
@ Override
Public String toString () {
Return "UserService {" +
"userDao=" + userDao +
'}'
}
}
However, if UserDao is null, it will cause UserService initialization to fail, which can be solved through ObjectProvider, as follows:
@ Service
Public class UserService {
Private UserDao userDao
Public UserService (ObjectProvider userDao) {
This.userDao = userDao.getIfUnique ()
}
@ Override
Public String toString () {
Return "UserService {" +
"userDao=" + userDao +
'}'
}
}
This is ObjectProvider. All right, let's go back to BeanFactory and continue to look at the methods in it.
ContainsBean
Determine whether the container contains a Bean.
IsSingleton
Determine whether a Bean is a singleton.
IsPrototype
Determine whether a Bean is a prototype.
IsTypeMatch
Returns whether the Bean of the specified name matches the specified type.
GetType
Returns the data type corresponding to the Bean of the specified name.
GetAliases
Returns the alias of Bean.
These are all the methods defined in BeanFactory, and you can see that they are basically container-related query methods, which will be implemented in the various implementation classes of BeanFactory.
3. Secondary interface
BeanFactory, as the top definition in the IoC container, does not inherit any interface. We can call it the first-level interface. There are three interfaces that directly inherit from BeanFactory, which we call the second-level interface.
3.1 HierarchicalBeanFactory
HierarchicalBeanFactory inherits from BeanFactory, defines factory layering, and extends two methods:
Public interface HierarchicalBeanFactory extends BeanFactory {
BeanFactory getParentBeanFactory ()
Boolean containsLocalBean (String name)
}
The getParentBeanFactory method returns the parent factory of the Bean factory, implementing factory layering. The containsLocalBean method determines whether the local factory contains the Bean.
HierarchicalBeanFactory has an interface ConfigurableBeanFactory,ConfigurableBeanFactory that inherits from HierarchicalBeanFactory and SingletonBeanRegistry, where SingletonBeanRegistry defines the definition of a singleton Bean and how to get it. In other words, ConfigurableBeanFactory has both factory layering and singleton processing functions. At the same time, the objects that getParentBeanFactory get to in HierarchicalBeanFactory are also configured in ConfigurableBeanFactory.
3.2 AutowireCapableBeanFactory
AutowireCapableBeanFactory, which inherits from BeanFacotory, extends the function of automatic assembly.
Public interface AutowireCapableBeanFactory extends BeanFactory {
Int AUTOWIRE_NO = 0
Int AUTOWIRE_BY_NAME = 1
Int AUTOWIRE_BY_TYPE = 2
Int AUTOWIRE_CONSTRUCTOR = 3
@ Deprecated
Int AUTOWIRE_AUTODETECT = 4
String ORIGINAL_INSTANCE_SUFFIX = ".Origin"
T createBean (Class beanClass) throws BeansException
Object createBean (Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException
Void autowireBean (Object existingBean) throws BeansException
Object autowire (Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException
Void autowireBeanProperties (Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException
Object configureBean (Object existingBean, String beanName) throws BeansException
Object initializeBean (Object existingBean, String beanName) throws BeansException
Void applyBeanPropertyValues (Object existingBean, String beanName) throws BeansException
Object applyBeanPostProcessorsBeforeInitialization (Object existingBean, String beanName) throws BeansException
Object applyBeanPostProcessorsAfterInitialization (Object existingBean, String beanName) throws BeansException
Void destroyBean (Object existingBean)
NamedBeanHolder resolveNamedBean (Class requiredType) throws BeansException
Object resolveBeanByName (String name, DependencyDescriptor descriptor) throws BeansException
@ Nullable
Object resolveDependency (DependencyDescriptor descriptor, @ Nullable String requestingBeanName) throws BeansException
@ Nullable
Object resolveDependency (DependencyDescriptor descriptor, @ Nullable String requestingBeanName)
@ Nullable Set autowiredBeanNames, @ Nullable TypeConverter typeConverter) throws BeansException
}
First of all, five different assembly strategies are defined through five constants, namely: non-automatic assembly, automatic assembly by name, automatic assembly by type, automatic assembly by construction method, and an out-of-date constant.
ORIGINAL_INSTANCE_SUFFIX is the suffix agreed upon when initializing the given name of the instance, which is added to the full path of the class, for example: com.mypackage.MyClass.ORIGINAL.
The createBean method is used to create the Bean instance; the autowire* method is used to complete the automatic assembly; the configureBean is used to configure the Bean;initializeBean to initialize the Bean;applyBeanPropertyValues and apply the BeanDefinition of the specified bean to an existing Bean; the applyBeanPostProcessorsBeforeInitialization/applyBeanPostProcessorsAfterInitialization calls the post processor of the Bean; and the destroyBean method is used to destroy the Bean;resolve* method to parse the Bean.
3.3 ListableBeanFactory
ListableBeanFactory inherits from BeanFacotory, and this interface lists all the instances that the factory can produce.
Public interface ListableBeanFactory extends BeanFactory {
Boolean containsBeanDefinition (String beanName)
Int getBeanDefinitionCount ()
String [] getBeanDefinitionNames ()
String [] getBeanNamesForType (ResolvableType type)
String [] getBeanNamesForType (ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit)
String [] getBeanNamesForType (@ Nullable Class type)
String [] getBeanNamesForType (@ Nullable Class type, boolean includeNonSingletons, boolean allowEagerInit)
Map getBeansOfType (@ Nullable Class type) throws BeansException
Map getBeansOfType (@ Nullable Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException
String [] getBeanNamesForAnnotation (Class
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.