In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 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 SpringBoot@EnableAutoConfiguration". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use SpringBoot@EnableAutoConfiguration.
Use posture
Talk about the posture before you talk about the principle.
Define a bean in project A.
Package com.wangzhi;import org.springframework.stereotype.Service;@Servicepublic class Dog {}
And create a file called spring.factories under the resources/META-INF/ of the project, which contains the following
Org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.wangzhi.Dog
Then reference project A's jar package in project B.
The projectA code is as follows:
Package com.wangzhi.springbootdemo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.annotation.ComponentScan;@EnableAutoConfigurationpublic class SpringBootDemoApplication {public static void main (String [] args) {ConfigurableApplicationContext context = SpringApplication.run (SpringBootDemoApplication.class, args); System.out.println (context.getBean (com.wangzhi.Dog.class));}}
Print the results:
Com.wangzhi.Dog@3148f668
Principle analysis
Overall, it is divided into two parts: one is to collect all the EnableAutoConfiguration-related bean classes in spring.factories, and the other is to register the resulting classes into the spring container.
Collect bean definition classes
When the spring container starts, AutoConfigurationImportSelector#getAutoConfigurationEntry is called
Attributes of protected AutoConfigurationEntry getAutoConfigurationEntry (AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {if (! isEnabled (annotationMetadata)) {return EMPTY_ENTRY;} / / EnableAutoConfiguration annotations: exclude,excludeName and other AnnotationAttributes attributes = getAttributes (annotationMetadata); / / get all Configurations List configurations = getCandidateConfigurations (annotationMetadata, attributes); / / deduplicated configurations = removeDuplicates (configurations); / / remove the specified class Set exclusions = getExclusions (annotationMetadata, attributes); checkExcludedClasses (configurations, exclusions); configurations.removeAll (exclusions); configurations = filter (configurations, autoConfigurationMetadata) FireAutoConfigurationImportEvents (configurations, exclusions); return new AutoConfigurationEntry (configurations, exclusions);}
GetCandidateConfigurations calls the method loadFactoryNames:
Public static List loadFactoryNames (Class factoryClass, @ Nullable ClassLoader classLoader) {/ / factoryClassName is org.springframework.boot.autoconfigure.EnableAutoConfiguration String factoryClassName = factoryClass.getName (); / / this method returns the classpath return loadSpringFactories (classLoader) .getOrDefault (factoryClassName, Collections.emptyList ()) where key is org.springframework.boot.autoconfigure.EnableAutoConfiguration in all spring.factories files;} public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories" Private static Map loadSpringFactories (@ Nullable ClassLoader classLoader) {MultiValueMap result = cache.get (classLoader); if (result! = null) {return result;} try {/ / find all the "META-INF/spring.factories" Enumeration urls = (classLoader! = null? ClassLoader.getResources (FACTORIES_RESOURCE_LOCATION): ClassLoader.getSystemResources (FACTORIES_RESOURCE_LOCATION); result = new LinkedMultiValueMap (); while (urls.hasMoreElements ()) {URL url = urls.nextElement (); UrlResource resource = new UrlResource (url); / / read the contents of the file. Properties is similar to HashMap and contains key and value Properties properties = PropertiesLoaderUtils.loadProperties (resource) of attributes; for (Map.Entry entry: properties.entrySet ()) {String factoryClassName = ((String) entry.getKey ()). Trim () / / you can use','to split multiple value for (String factoryName: StringUtils.commaDelimitedListToStringArray ((String) entry.getValue () {result.add (factoryClassName, factoryName.trim ());} cache.put (classLoader, result); return result;} catch (IOException ex) {throw new IllegalArgumentException ("Unable to load factories from location [" + FACTORIES_RESOURCE_LOCATION + "], ex);}}
Register to the container
The classpath of all the bean specified in spring.factories is obtained in the above process, which is imported into the container in the same logic as the @ import annotation in the processGroupImports method.
Public void processGroupImports () {for (DeferredImportSelectorGrouping grouping: this.groupings.values ()) {/ / getImports is the encapsulation of all the classpath obtained above grouping.getImports (). ForEach (entry-> {ConfigurationClass configurationClass = this.configurationClasses.get (entry.getMetadata ()); try {/ / processImports (configurationClass, asSourceClass (configurationClass), asSourceClasses (entry.getImportClassName (), false);} catch (BeanDefinitionStoreException ex) {throw ex) } catch (Throwable ex) {throw new BeanDefinitionStoreException ("Failed to process import candidates for configuration class [" + configurationClass.getMetadata (). GetClassName () + "], ex);}}) }} private void processImports (ConfigurationClass configClass, SourceClass currentSourceClass, Collection importCandidates, boolean checkForCircularImports) {. / / traverse the collected classpath for (SourceClass candidate: importCandidates) {. / / if candidate is of ImportSelector or ImportBeanDefinitionRegistrar type, its processing logic will be different. We don't care about / / Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar-> / / process it as an @ Configuration class this.importStack.registerImport (currentSourceClass.getMetadata (), candidate.getMetadata (). GetClassName ()). / / treat processConfigurationClass (candidate.asConfigClass (configClass)) as @ Configuration;.}.}
As you can see, the bean class definitions collected in the first step will eventually be registered with the container in the same way as Configuration.
End
The @ EnableAutoConfiguration annotation simplifies the cost of importing bean from a second-party package. To provide a second-party package for other applications, you only need to define the exposed bean in the spring.factories in the second-party package. Unwanted bean can be excluded by using the @ EnableAutoConfiguration exclude attribute of the user.
At this point, I believe that you have a deeper understanding of "the use of SpringBoot@EnableAutoConfiguration", you might as well come to the actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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: 222
*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.