Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring extension points

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use Spring extension points". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to use Spring extension points".

Spring common extension point "BeanFactoryPostProcessor#postProcessBeanFactory"

Sometimes there are hundreds of bean in the whole project, and most of the single test depends on the xml of the whole project, resulting in a long time for single test execution (most of the time is spent on the instantiation and initialization process of hundreds of single non-lazily loaded bean in xml).

Solution: use the extension point provided by Spring to set the bean in xml to lazy loading mode, saving the instantiation and initialization time of Bean

Public class LazyBeanFactoryProcessor implements BeanFactoryPostProcessor {@ Override public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException {DefaultListableBeanFactory fac = (DefaultListableBeanFactory) beanFactory; Map map = (Map) ReflectionTestUtils.getField (fac, "beanDefinitionMap"); for (Map.Entry entry: map.entrySet ()) {/ / set to lazy load entry.getValue (). SetLazyInit (true);}

"InstantiationAwareBeanPostProcessor#postProcessPropertyValues"

Unconventional configuration items such as

Spring provides a special parser corresponding to it

It is through these special parsers that the corresponding configuration items can take effect.

The parser configured for this particular configuration is ComponentScanBeanDefinitionParser

In the parsing method of this parser, many special Bean are registered

Public BeanDefinition parse (Element element, ParserContext parserContext) {/ /. RegisterComponents (parserContext.getReaderContext (), beanDefinitions, element); / / Return null;} public static Set registerAnnotationConfigProcessors (BeanDefinitionRegistry registry, Object source) {Set beanDefs = new LinkedHashSet (4); /... / @ Autowire if (! registry.containsBeanDefinition (AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition (AutowiredAnnotationBeanPostProcessor.class); def.setSource (source); beanDefs.add (registerPostProcessor (registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) } / / Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. / / @ Resource if (jsr250Present & &! registry.containsBeanDefinition (COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {/ / Special Bean RootBeanDefinition def = new RootBeanDefinition (CommonAnnotationBeanPostProcessor.class); def.setSource (source); beanDefs.add (registerPostProcessor (registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));} / /. Return beanDefs;}

Take @ Resource as an example to see what this particular bean has done.

Public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {public PropertyValues postProcessPropertyValues (PropertyValues pvs, PropertyDescriptor [] pds, Object bean, String beanName) throws BeansException {InjectionMetadata metadata = findResourceMetadata (beanName, bean.getClass ()); try {/ / attribute injection metadata.inject (bean, beanName, pvs) } catch (Throwable ex) {throw new BeanCreationException (beanName, "Injection of resource dependencies failed", ex);} return pvs;}}

We see that attribute injection is done in the postProcessPropertyValues method

"invokeAware"

For a class that implements the BeanFactoryAware interface, the container executes the setBeanFactory method to inject the current container BeanFactory into the class

@ Bean class BeanFactoryHolder implements BeanFactoryAware {private static BeanFactory beanFactory; public void setBeanFactory (BeanFactory beanFactory) throws BeansException {this.beanFactory = beanFactory;}}

"BeanPostProcessor#postProcessBeforeInitialization"

For a class that implements the ApplicationContextAware interface, the container executes the setApplicationContext method to inject the current container applicationContext into the class

Bean class ApplicationContextAwareProcessor implements BeanPostProcessor {private final ConfigurableApplicationContext applicationContext; public ApplicationContextAwareProcessor (ConfigurableApplicationContext applicationContext) {this.applicationContext = applicationContext;} @ Override public Object postProcessBeforeInitialization (final Object bean, String beanName) throws BeansException {/ /. InvokeAwareInterfaces (bean); return bean;} private void invokeAwareInterfaces (Object bean) {if (bean instanceof ApplicationContextAware) {((ApplicationContextAware) bean) .setApplicationContext (this.applicationContext);}

We see that the call to the setApplicationContext method is made in the postProcessBeforeInitialization of BeanPostProcessor

Class ApplicationContextHolder implements ApplicationContextAware {private static ApplicationContext applicationContext; public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}}

"afterPropertySet () and init-method"

At present, many Java middleware are built by basic Spring Framework, and these middleware often put the entry into afterPropertySet or custom init.

"BeanPostProcessor#postProcessAfterInitialization"

Students who are familiar with aop should know that the underlying layer of aop is implemented through dynamic agents.

When configured, the aop function is enabled by default, and accordingly, the objects that the caller needs to be woven into by aop need to be replaced with dynamic proxy objects.

Have you ever thought about how the dynamic proxy "replaces the original object without the caller's perception"?

Based on the above explanation, we know:

Spring also provides a special parser, which, like other parsers, registers a special bean in the core parse method

Here is a bean of type BeanPostProcessor

Class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser {@ Override public BeanDefinition parse (Element element, ParserContext parserContext) {/ / register a special bean AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary (parserContext, element); extendBeanDefinition (element, parserContext); return null;}}

The dynamic proxy object corresponding to the current bean is returned, and the process is all transparent to the caller.

Public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException {if (bean! = null) {Object cacheKey = getCacheKey (bean.getClass (), beanName); if (! this.earlyProxyReferences.containsKey (cacheKey)) {/ / if the class needs to be proxied, return the dynamic proxy object Otherwise, return the original object return wrapIfNecessary (bean, beanName, cacheKey);}} return bean;}}

It is this extension point of Spring that implements the replacement of dynamic proxy objects.

"destroy () and destroy-method"

The last extension point in the bean life cycle, which is used to perform some preparatory work before bean destruction, such as releasing some resources currently held by bean.

Thank you for your reading, the above is the content of "how to use Spring extension point", after the study of this article, I believe you have a deeper understanding of how to use Spring extension point, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report