في الوقت الذي تحظى فيه Spring Cloud بشعبية ، يكون الأمر مربكًا للغاية إذا كنت لا تفهم المبادئ الأساسية (كل ما تراه هي اتفاقيات أكبر من التكوين ، ولكن ماذا عن المبدأ؟ لماذا تحتاج إلى القيام بذلك؟). تم بناء سحابة الربيع بسرعة على أساس الحذاء الربيعي. اليوم سوف نلقي نظرة على عملية بدء تشغيل حاوية SPRING. (لا تشرح هذه المقالة كيفية بدء تشغيل Spring Boot بسرعة ، فقط اقرأ تلك المقالة مباشرة على الموقع الرسمي ، وتوثيق التذاكر الرسمية على الموقع الإلكتروني)
يحدد SPRING BOOT عمومًا الحاوية لبدء الطريقة الرئيسية ثم بدء تشغيل حزمة الجرة في سطر الأوامر ، كما هو موضح في الشكل أدناه:
springbootapplicationpublicpublic application {public static void main (string [] args) {springapplication.run (application.class ، args) ؛ }}هنا شيئان:
1. @springbootapplication شرح
2. springapplication.run () طريقة ثابتة
دعنا نستكشف هذين المحتلين بشكل منفصل أدناه.
رمز المصدر كما يلي:
target (elementType.type) retention (attreentionpolicy.runtime) documented inheritedBringBootConfiguration enableaUtoconFigurationSCOMPONENTSCAN (isscluedFilters = {filter (type = filtertype.custom ، classes = typeExClaSt filterType.custom ، الفئات = autoConFigurationExCludeFilter.Class)}) public interface springbootapplication {الملاحظات الأساسية:
springbootConfiguration (في الواقع configuration): يعني أن هذه فئة تكوين JavaconFig ، يمكنك تخصيص الفاصوليا ، التبعيات ، إلخ في هذه الفئة. -》 هذا شرح فريد من نوعه للبوت الربيعة ويتم استخدامه بشكل شائع.
enabeautoconfiguration: بمساعدة @import ، قم بتحميل جميع تعريفات الفاصوليا التي تلبي معايير التكوين التلقائي في حاوية IOC (يوصى بوضعها تحت مسار حزمة الجذر ، بحيث يمكن مسح الحالات الفرعية والفئات). -》 هذا يتطلب حفر تفصيلي!
componentscan: التعليق التوضيحي التلقائي للمسح الضوئي ، والذي يمكن أن يحدد نطاق المسح وتحميله في حاوية IOC. -》 لم يعد قول هذا ، يجب أن يكون الجميع على دراية بتعليقات الربيع.
رمز المصدر للشرح enbeautoconfiguration:
suppressWarnings ("deprecation") target (elementType.type) receent (attreencepolicy.runtime) documented inheritedautoConfigurationPackAgeAtiMport (enableeautoconfigurationImportselector.class) public enialeaToconFiguration {النواة عبارة عن مخطط فئة EnableAutoconfigurationImportselector على النحو التالي:
تم تحديد الطريقة الأساسية لـ Imports () في مستفيدة المستورد للواجهة العليا ، فإن الكود المصدري هو كما يلي:
Override public string [] SelectImports (annotationMetadata annotationMetAdata) {if (! isEnabled (annotationMetadata)) {return no_imports ؛ } حاول {// 1. تحميل 483 خصائص التكوين من ملف meta-inf/spring-autoconfigure-metadata.properties (بعضها له قيم افتراضية) ، autoConfigurationMetAdata autoconfigurationMutAdata = autoconfigurationmetadataloader. esentationAttributes سمات = getAttributes (annotationMetadata) ؛ // 2. احصل على قائمة سمات التعليقات التوضيحية <string> التكوينات = getCandidateConfigurations (التعليق التوضيحي ، // 3. احصل على 97 سمات فئات التكوين التلقائية) ؛ التكوينات = تم إزالتها (تكوينات) ؛ // 4. قم بإزالة التكوينات المكررة = الفرز (التكوينات ، autoConfigurationMetAdata) ؛ // 5. SITE SET SET <STRING> excludes = getExClusions (التعليق التوضيحي ، السمات) ؛ // 6. احصل على checkexcludedclasses (التكوينات ، تستبعد) ؛ // 7. تحقق من تكوينات الفئة المستبعدة. RemoVeall (استثناءات) ؛ // 8. احذف جميع التكوينات التي يجب استبعادها = التصفية (التكوينات ، autoConfigurationMetAdata) ؛ // 9. لا ساري المفعول بالمرشح onClassCondition (المكون في التعليقات التوضيحية عند وجود فئة معينة). توجيه تكوينات الاستماع التلقائية للتكوين الاستماع إلى تكوينات الإرجاع. toarray (سلسلة جديدة [configurations.size ()]) ؛ } catch (ioException ex) {refl new alficalstateException (ex) ؛ }}فيما يلي 3 طرق أساسية:
1) تكوين تحميل LoadMetadata
في الواقع ، هو استخدام محمل فئة للتحميل: meta-inf/spring-autoconfigure-metadata.properties (spring-boot-autoconfigure-1.5.9
2) GetCandidateConfigurations احصل على قائمة أسماء فئة التكوين التلقائية المدعومة الافتراضية
تلقائيًا تكوين طريقة Soul ، SPRINGFACTIRASERS.LOADFACTORYNAMES الحصول على تكوين مفتاح فئة التكوين التلقائي = ENALEAUTOCONFIGIRATION.CLASS من ملف meta-inf/spring.factories (spring-boot-autoconfigure-1.5.9.release-sources.jar).
القائمة المحمية <string> getCandidateConfigurations (التعليق التوضيحي metadata ، annotationattributes) {// هذا صحيح ، المعلمتان هنا عديمة الفائدة ... يمكنها شرحها لي ... قائمة <Tring> configurations = springfactoriesLoader.LoadFactoryNames (gettpringfactoristoristory () Assert.Notempty (التكوينات ، "لا توجد فئات تكوين تلقائية موجودة في meta-inf/spring.factories. إذا كنت تستخدم" + "عبوة مخصصة ، فتأكد من أن الملف صحيح.") ؛ إرجاع تكوينات ؛ }. }ماذا حصلت بالفعل؟ ملف Spring.Factories كما يلي ، والذي يحصل فعليًا على جميع فئات وحدة التكوين التلقائي لتكوين #AUTO.
# Initializersorg.springframework.context.ApplicationContextInitializer=/org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,/org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer# Application المستمعين. المستمعين. filtersorg.springframework.boot.autoconfigure.autoconFigurationImportFilter =/org.springframework.boot.autoconfigure.condition.onclasscondition# تكوين تلقائي هنا جميع فصول التكوين التلقائي org.springframework.boot.autoconfigure.enableautoconfiguration =/org.springframework.boot.autoconfigure.admin.spr ingapplicationAdminjmxautoconfiguration ،/org.springframework.boot.autoconfigure.aop.aopautoconfiguration ،/org.spr ingframework.boot.autoconfigure.amqp.Rabbitautoconfiguration ،/org.springframework.boot.autoconfigure.batch.batchautocon الشكل ،/org.springframework.boot.autoconfigure.cache.cacheautoconfiguration ،/org.springframework.boot.autoconfigure .cassandra.cassandraautoconfiguration ،/org.springframework.boot.autoconfigure.cloud.cloudautoconfiguration ،/org.spring framework.boot.autoconfigure.context.ConfigurationPropertiesAutoconFiguration ،/org.springframework.boot.autoconfigure.c ontext.messagesourceautoconfiguration ،/org.springframework.boot.autoconfigure.context.propertyplyderautoconfigurat أيون ،/org.springframework.boot.autoconfigure.couchbase.couchbaseautoconfiguration ،/org.springframework.boot.autoconfigur e.dao.persistenceexceptiontranslationautoconfiguration ،/org.springframework.boot.autoconfigure.data.cassandra.cassandr adataautoconfiguration ،/org.springframework.boot.autoconfigure.data.cassandra.cassandrarepositoriesautoconfiguration ،/o rg.springframework.boot.autoconfigure.data.couchbase.couchbasedataautoconfiguration ،/org.springframework.boot.autoconfi gure.data.couchbase.couchbaserepositoriesautoconfiguration ،/org.springframework.boot.autoconfigure.data.elasticsearch.e lasticsearchautoconfiguration ،/org.springframework.boot.autoconfigure.data.elasticsearch.elasticsearchDataUutoConfiguration ،/org.springframework.boot.autoconfigure.data.elasticsearcherearch.springconforties Ramework.boot.autoconfigure.data.jpa.jparepositoriesautoconfiguration ،/org.springframework.boot.autoconfigure.data.ldap .ldapdataautoconfiguration ،/org.springframework.boot.autoconfigure.data.ldap.ldapropositoriesautoConfiguration ،/org.spr ingframework.boot.autoconfigure.data.mongo.mongodataautoconfiguration ،/org.springframework.boot.autoconfigure.data.mon go.mongorepositoriesautoconfiguration ،/org.springframework.boot.autoconfigure.data.neo4j.neo4jdataautoconfiguration ،/أو g.springframework.boot.autoconfigure.data.neo4j.neo4jrepositoriesautoconfiguration ،/org.springframework.boot.autoconfig ure.data.solr.solrrepositoriesautoconfiguration ،/org.springframework.boot.autoconfigure.data.redis.redisautoconfigurati على ،/org.springframework.boot.autoconfigure.data.redis.redisRepositoriesAutoconFiguration ،/org.springframework.boot.auto configure.data.rest.repositoryrestmvcautoconfiguration ،/org.springframework.boot.autoconfigure.data.web.springdatawebau toConfiguration ،/org.springframework.boot.autoconfigure.elasticsearch.jest.jestautoconfiguration ،/org.springframework.b oot.autoconfigure.freemarker.freemarkerautoconfiguration ،/org.springframework.boot.autoconfigure.gson.gsonautoconfigura نشوئها ،/org.springframework.boot.autoconfigure.h2.h2consoleautoconfiguration ،/org.springframework.boot.autoconfigure.hateoas.hypermediaautoconfiguration ،/org.sp ringframework.boot.autoconfigure.hazelcast.hazelcastautoconfiguration ،/org.springframework.boot.autoconfigure.hazelcast.hazelcastautoconfiguration ،/org.spring ngframework.boot.autoconfigure.hazelcast.hazelcastjpadependencyautoconfiguration ،/org.springframework.boot.autoconfigur e.info.projectinfoautoconfiguration ،/org.springframework.boot.autoconfigure.integration.integrationautoconfiguration ،/o rg.springframework.boot.autoconfigure.jackson.jacksonautoconfiguration ،/org.springframework.boot.autoconfigure.jdbc.dat asourceautoconfiguration ،/org.springframework.boot.autoconfigure.jdbc.jdbctemplateautoconfiguration ،/org.springframewor k.boot.autoconfigure.jdbc.jndidatasourceautoconfiguration ،/org.springframework.boot.autoconfigure.jdbc.xadataTasourceauto التكوين ،/org.springframework.boot.autoconfigure.jdbc.datasourCetransActionManagerautoconfiguration ،/org.springfra mework.boot.autoconfigure.jms.jmsautoconfiguration ،/org.springframework.boot.autoconfigure.jmx.jmxautoconfiguration ،/o rg.springframework.boot.autoconfigure.jms.jndiconnectionfactoryautoconfiguration ،/org.springframework.boot.autoconfigur e.jms.activemq.activemqautoconfiguration ،/org.springframework.boot.autoconfigure.jms.aremis.artemisautoconfiguration ،/ org.springframework.boot.autoconfigure.flyway.flywayautoconfiguration ،/org.springframework.boot.autoconfigure.groovy.te mplate.groovytemplateautoconfiguration ،/org.springframework.boot.autoconfigure.jersey.jerseyautoconfiguration ،/org.springframework.boot.autoconfigure.joo : guration ،/org.springframework.boot.autoconfigure.ldap.embedded.embeddedddlapautoconfiguration ،/org.springframework.boot. autoconfigure.ldap.ldapautoconfiguration ،/org.springframework.boot.autoconfigure.liquibase.liquibaseautoconfiguration ،/ org.springframework.boot.autoconfigure.mail.mailsenderautoconfiguration ،/org.springframework.boot.autoconfigure.mail.m Ailsendervalidatorautoconfiguration ،/org.springframework.boot.autoconfigure.mobile.deviceresolverautoconfiguration ،/org .springframework.boot.autoconfigure.mobile.devicedelegatingViewResolverautoConfiguration ،/org.springframework.boot.auto config.mobile.sitepreferenceautoconfiguration ،/org.springframework.boot.autoconfigure.mongo.embedded.embeddedmongoau toConfiguration ،/org.springframework.boot.autoconfigure.mongo.mongoautoconfiguration ،/org.springframework.boot.autoconf igure.mustache.mustacheautoconfiguration ،/org.springframework.boot.autoconfigure.orm.jpa.hibernatejpaautoconfiguration ، /org.springframework.boot.autoconfigure.Reactor.ReactorautoconFiguration ، framework.boot.autoconfigure.security.SecurityFilterautoconfiguration ،/org.springframework.boot.autoconfigure.security.securityfilterautoconfiguration ،/org.spri ngframework.boot.autoconfigure.security.fallbackwebsecurityautoconfiguration ،/org.springframework.boot.autoconfigure.security.oauth2auth2autoconfiguration ،/org.springframework.boot.autoconfigure.sendgrid.sendgridautoconfiguration ،/org.springframework.boot.autoconfigure.sendgrid.sendgridautoconfiguration ،/org. springframework.boot.autoconfigure.session.sessionautoconfiguration ،/org.springframework.boot.autoconfigure.social.soci alwebautoconfiguration ،/org.springframework.boot.autoconfigure.social.facebookautoconfiguration ،/org.springframework.bo ot.autoconfigure.social.linkedinautoconfiguration ،/org.springframework.boot.autoconfigure.social.twitterautoconfigurati على ،/org.springframework.boot.autoconfigure.solr.solrautoconfiguration ،/org.springframework.boot.autoconfigure.thymeleaf .Thymeleafautoconfiguration ،/org.springframework.boot.autoconfigure.transaction.transactionautoconfiguration ،/org.sprin gframework.boot.autoconfigure.transaction.jta.jtaautoconfiguration ،/org.springframework.boot.autoconfigure.validation.v alidationautoconfiguration ،/org.springframework.boot.autoconfigure.web.dispatcherservletautoconfiguration ،/org.springf Ramework.boot.autoconfigure.web.embedservletcontainerautoconfiguration ،/org.springframework.boot.autoconfigure.web.e errormvcautoconfiguration ،/org.springframework.boot.autoconfigure.web.httpencodingautoconfiguration ،/org.springframewor k.boot.autoconfigure.web.httpmessageconvertersautoconfiguration ،/org.springframework.boot.autoconfigure.web.multipartaut oconfiguration ،/org.springframework.boot.autoconfigure.web.serverpropertiesautoconfiguration ،/org.springframework.boot.autoconfigure.web.webclientautoconfiguration ،/org.s pringframework.boot.autoconfigure.websocket.websocketautoConfiguration ،/org.springframework.boot.autoconfigure.websocket.websocketMessArageConficServicesaToConficServiceToConficServiceToConficesToCtOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctOctoT Analyzersorg.springframework.boot.diagnostics.failureanalyzer =/org.springframework.boot.autoconfigure.diagnostics.analyzer.nosuchbeandefinitionfailureanalyzer ،/org. springframework.boot.autoconfigure.jdbc.dataSourceBeanCreationFailureAnalyzer ،/org.springframework.boot.autoconfigure.jdbc.hikaridriverconfigurationfailer توافر القالب Providersorg.springframework.boot.autoconfigure.template.templateavailabilityprovider =/org.springframework.boot.autoconfigure.fre emarker.freemarkertemplateavailabilityprovider ،/org.springframework.boot.autoconfigure.mustache.mustachetemplateavailabilityprovi der ،/org.springframework.boot.autoconfigure.groovy.template.groovytemplateavailabilityprovider ،/org.springframework.boot.autoconf igure.Thymeleaf.Thymeleaftemplateavailabilityprovider ،/org.springframework.boot.autoconfigure.web.jsptemplateavailabilityprovider
3) يقوم مرشح المرشح بتصفية الشروط التي لا تفي بتعليقات OnClassCondition
قائمة خاصة <string> مرشح (قائمة <Tring> التكوينات ، autoConFigurationMetAdata autoConfigurationMetAdata) {long startTime = system.nanotime () ؛ string [] Coygulates = configurations.toarray (سلسلة جديدة [configurations.size ()]) ؛ Boolean [] Skip = New Boolean [Conversity.Length] ؛ تخطي منطقية = خطأ ؛ // احصل على اعتراض استيراد التكوين التلقائي الذي يجب ترشيحه ، لا يوجد سوى واحد في Spring.Factories تكوين: org.springframework.boot.autoconfigure.condition.onclassCondition لـ (autoConfigurationImportFilter filter: getAutoconFigurationImportFilters Boolean [] match = filter.match (المرشحين ، autoConfigurationMetAdata) ؛ لـ (int i = 0 ؛ i <match.length ؛ i ++) {if (! match [i]) {skip [i] = true ؛ تخطي = صحيح ؛ }}} إذا (! تخطي) {// طالما كان هناك عدم تطابق واحد -> تخطي = صحيح ، جميع المطابقات -》 تخطي = false-> العودة مباشرة لإرجاع التكوينات ؛ } قائمة <String> result = new ArrayList <String> (Canneridates.Length) ؛ من أجل (int i = 0 ؛ i <canneridates.length ؛ i ++) {if (! skip [i]) {// match-》 لا تخطي》 add إلى result.add (المرشحين [i]) ؛ }} if (logger.istraceenabled ()) {int numberfiltered = configurations.size () - result.size () ؛ logger.trace ("fultled" + numberFiltered + "Configuration Auto Class في" + timeUnit.nanoseconds.tomillis (system.nanotime () - startTime) + "MS") ؛ } إرجاع ArrayList جديد <string> (النتيجة) ؛ }springapplication.run
public configurableApplicationContext Run (String ... args) {STOPTWATCH STVENTWATCH = NEW STOPTWATCH () ؛ توقيت. ستارت () ؛ configurableApplicationContext context = null ؛ alualureanalyzers محللون = فارغ ؛ ConfigureDheadlessProperty () ؛ springapplicationRunlisteners المستمعين = getRunListeners (args) ؛ // 1. احصل على مستمع المستمعين. الابتعاد () ؛-> ابدأ! جرب {ApplicationArguments ApplicationArguments = defaultApplicationArguments (args) ؛ بيئة البيئة القابلة للتكوين = إعداد البيئة (المستمعين ، // 2. إعداد البيئة وإطلاق ApplicationenVironmentPreparedEvent ApplicationArguments) ؛ Banner printedbanner = printbanner (البيئة) ؛ // طباعة حرف مطالبة بدء التشغيل ، سياق مخطط حرف الربيع الافتراضي = createApplicationContext () ؛ // instantiate a analyzers context Application Application = New FailureAnalyzers (السياق) ؛ prepareContext (السياق ، البيئة ، المستمعين ، ApplicationArguments ، // 3. إعداد السياق printedbanner) ؛ RefreshContext (السياق) ؛ // 4. قم بتحديث السياق اللاحق بعد ذلك (السياق ، ApplicationArguments) ؛ // 5. بعد تحديث المستمعين السياق. ساعة توقيت. stop () ؛ if (this.logstartupinfo) {new StartupInfologger (this.mainapplicationClass) .logStarted (getApplicationLog () ، stalpwatch) ؛ سياق الإرجاع ؛ } catch (throwable ex) {handlerunfailure (السياق ، المستمعون ، المحللون ، ex) ؛ رمي الجديد غير القانوني stateException (ex) ؛ }}1.
إنها في الواقع فئة SpringApplicationRunListener
SpringApplicationRunListeners GetRunListeners (String [] args) {class <؟> [] types = class new <؟> [] {springapplication.class ، string []. class} ؛ إرجاع springapplicationrunlisteners جديد (logger ، getSpringFactoriesInstances (SpringApplicationRunListener.class ، that ، this ، args)) ؛ } private <t> collection <؟ يمتد t> getSpringFactoriesInstances (الفئة <T> type) {return getSpringFactoriesInstances (type ، فئة جديدة <؟> [] {}) ؛ } private <t> collection <؟ يمتد t> getSpringFactoriesInstances (الفئة <t> النوع ، الفئة <؟> [] parametertypes ، الكائن ... args) {classloader classloader = thread.currentThread (). getContextClasslader () ؛ // استخدم SET لضمان تفرد مجموعة الأوتار <STRING> NAMES = NEW LinkedHashSet <String> (SpringFactoriesLoader.LoadFactoryNames (type ، classloader)) ؛ // 1. قم بتحميل قائمة مجموعة مصنع <T> instances = CreateSpringFactoriesInstances (type ، parametertypes ، // 2. التعليقات التوضيحية ContingOrderComparator.sort (مثيلات) ؛ // فرز مثيلات الإرجاع ؛ }1.1 اسم مصنع التحميل (LoadFactoryNames)
يحصل محمل الفئة للفئة الحالية على تكوين فئة SpringApplicationRunListener من ملف meta-inf/spring.factories
قائمة ثابتة عامة <string> loadFactoryNames (الفئة <؟> Factoryclass ، classloader classloader) {String FactoryClassName = Factoryclass.getName () ؛ جرب {enumeration <Url> urls = (classloader! = null؟ classloader.getResources (factories_resource_location): classloader.getSystemResources (factories_resource_location)) ؛ قائمة <Tring> result = new ArrayList <String> () ؛ بينما (urls.hasmoreElements ()) {url url = urls.nextElement () ؛ خصائص الخصائص = PropertiesLoaderUtils.LoadProperties (URLResource (URL)) ؛ String FactoryClassNames = properties.getProperty (FactoryClassName) ؛ result.addall (Arrays.aslist (StringUtils.CommadElimitedListTtoStringArray (FactoryClassNames))) ؛ } نتيجة الإرجاع ؛ } catch (ioException ex) {refl new alficalArgumentException ("غير قادر على تحميل [" + factoryclass.getName () + "] المصانع من الموقع [" + factories_resource_location + "] ، ex) ؛ }}في الصورة أعلاه ، بعد الحصول على اسم فئة المصنع ، دعونا نلقي نظرة على ما هو محدد في meta-inf/spring.factories:
# propertysource loadersorg.springframework.boot.env.propertysourceloader =/org.springframework.boot.env.propertiespropertysourceloader ،/org.springframework.boot.env.yamlpropertysourcoader ! ! ! org.springframework.boot.springapplicationRunListener =/org.springframework.boot.context.event.eventpublishRunListener# سياق التطبيق initializersorg.springframework.context.applicationContextInitializer =/org.springframework.boot.context ApplicationContextInitializer ،/org.springframework.boot.context.config.delegatingapplicationContextInitializer ،/org.springframework.boot.context.embedded.serverportinfoapplicationContinitializer# leadersorg.springframework.context.applicationListener =/org.springframework.boot.clearcachesapplicationLitive ،/org.springframework.boot.builder.parentContextCloserap plicationListener ،/org.springframework.boot.context.fileencodingapplicationListener ،/org.springframework.boot.context.config.ansioutputapplicationlication ،/org.springfra mework.boot.context.config.configfileApplicationListener ،/org.springframework.boot.context.config.delegatingapplicationlistener ،/org.springframework.boot.liquibase.liqui BaseservicElocatorAppLicationLicationListener ،/org.springframework.boot.logging.classpathloggingapplicationlicationlicallistener ،/org.springframework.boot.logging.loggingapplicationlistener# البيئة ما بعد المعالجات. Analyzersorg.springframework.boot.diagnostics.failureanalyzer =/org.springframework.boot.diagnostics.analyzer.beancurtienCreationFailureAnalyzer ،/org. springframework.boot.diagnostics.analyzer.beannotofrequiredtypailureanalyzer ،/org.springframework.boot.diagnostics.analyzer.bindfailureanalyzer ،/org.spr ingframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer ،/org.springframework.boot.diagnostics.analyzer.nouniquebeandefinitionfailureanalyzer ، /org.springframework.boot.diagnostics.analyzer.portinusefailureanalyzer ، FailureAnalysisReportersorg.springframework.boot.diagnostics.failureanalysisReporter =/org.springframework.boot.diagnostics.loggingFailureAnalysisReporter
واو ، كل هذه الفئات لها أسماء كاملة ، والمفاتيح هي واجهات ، والقيم هي فئات التنفيذ. نحصل على قيمة فئة التنفيذ = "org.springframework.boot.springapplicationRunListener" استعلام بناءً على المفتاح = "org.springframework.boot.context.event.eventPublichingRunlistener" إصدار الحدث وبدء المستمع. بمجرد تخمينك ، يجب عليك استخدام "انعكاس" للحصول على مثيل الفصل بناءً على اسم الفصل. تم التحقق من ما يلي بسرعة ...
1.2 إنشاء مثيلات مصنع الربيع
قم بإنشاء مثيل مصنع "EventPublishing START BASTORER" استنادًا إلى مجموعة الأسماء <String> (سلسلة التنفيذ الوحيدة EventPublishingRunListener من SpringApplicationRlistener) التي تم الحصول عليها في الخطوة الأولى
suppressWarnings ("unchected") private <t> قائمة <T> CreateSpringFactoriesInstances (الفئة <t> النوع ، الفئة <؟> [] parametertytypes ، classloader classloader ، object [] args ، set <string> names) {list <t> instances = new arraylist <T> (names.size () ؛ لـ (اسم السلسلة: الأسماء) {try {class <؟> instanceclass = classutils.forname (name ، classloader) ؛ // استخدم الانعكاس للحصول على الفئة Assert.isAsisignable (النوع ، instanceclass) ؛ مُنشئ <؟> مُنشئ = instanceclass .getDeclaredConstructor (parametertypes) ؛ // الحصول على مثيل المُنشئ t = (t) beanutils.instantiateclass (مُنشئ ، args) ؛ // عوالم بنية بناءً على الحالات المُنشئة والمعلمات (مثال) ؛ } catch (throwable ex) {refl new alficalArgumentException ("لا يمكن إنشاء" + type + ":" + name ، ex) ؛ }} مثيلات الإرجاع ؛ }إعداد السياق
private void prepareContext (ConfigurableApplicationContext Context ، BehysibleenVironment Behysing ، springapplicationrunlisteners مستمعين ، تطبيقات ApplicationArguments ، banner printedbanner) {context.setenvironment (البيئة) ؛ postprocessapplicationContext (السياق) ؛ // singleton a beannamegenerator ، قم بتعيين resourceloader في سياق التطبيق تطبيق appliciitializers (السياق) ؛ باطل)؛ logstartupprofileInfo (السياق) ؛ }. if (printedbanner! = null) {context.getBeanFactory (). restersingleton ("Springbootbanner" ، printedbanner) ؛ } // تحميل مجموعة الموارد <Object> المصادر = getSources () ؛ تأكيد. notempty (المصادر ، "يجب ألا تكون المصادر فارغة") ؛ load (Context ، Sources.ToArray (comple new [sources.size ()])) ؛ المستمعين. context (سياق) ؛ // ينفذ المستمع طريقة "السياق المحملة"}تحديث السياق
private void refreshContext (configurableApplicationContext Context) {refresh (context) ؛ // core class if (this.registerShutDownHook) {try {context.registershutdownhook () ؛ // تسجيل خطاف الإغلاق ، يتم تنفيذه عند إغلاق الحاوية} catch (AccessControlexception ex) {// غير مسموح به في بعض البيئة. }}} تحديث باطل محمي (ApplicationContext ApplicationContext) {Assert.isinstanceof (AbstractapplicationContext.class ، ApplicationContext) ؛ ((AbstractApplicationContext) ApplicationContext) .refresh () ؛ }التنفيذ النهائي هو طريقة التحديث لفئة ملخص AbstractApplicationContext.
تحديث الفراغ العام () يلقي beansexception ، alfortstateException {Synchronized (this.startupshutdownitor) {// الاستعداد لتحديث بيئة السياق ، مثل إعداد خصائص النظام والتحقق منها أو متغيرات البيئة. prepareRefresh () ؛ // ابدأ طريقة RefreshBeanfactory للكاسورة الفرعية. parses xml configurableListableBeanfactory beanfactory = getfreshbeanfactory () ؛ // تكوين ميزات الحاوية لـ Beanfactory ، مثل تحميل الفئة ، معالج الأحداث ، إلخ. جرب {// تعيين ما بعد المعالجة من الفول. طريقة فارغة ، اتركها لتوسع الفئة الفرعية. postprocessbeanfactory (Beanfactory) ؛ // اتصل بـ Postprocessors of Beanfactory ، والتي يتم تسجيلها في الحاوية في تعريف الفول. InvokebeanfactoryPostProcessors (Beanfactory) ؛ // سجل ما بعد المعالج من الفول واتصل به أثناء عملية إنشاء الفول. registerBeanPostProcessors (Beanfactory) ؛ // تهيئة مصدر الرسائل في السياق ، أي أن أجسام الرسائل بلغات مختلفة تتم معالجتها دوليًا initMessagesource () ؛ // تهيئة ApplicationEventMulticaster Bean ، ومذيع حدث التطبيق هو initapplicationeventmulticaster () ؛ // تهيئة الفاصوليا الخاصة الأخرى ، والطرق الفارغة ، واتركها لتوسيع الفئة الفرعية. onrefresh () ؛ // تحقق وتسجيل مستمع Bean Recordlisteners () ؛ // مثيل جميع الفول المتبقي (غير لامع). الانتهاء من beanfactoryinitialization (beanfactory) ؛ // نشر أحداث الحاوية وإنهاء عملية التحديث. FinishRefresh () ؛ } catch (beansexception ex) {if (logger.iswarnenabled ()) {logger.warn ("استثناء تمت مواجهته أثناء تهيئة السياق -" + "إلغاء محاولة التحديث:" + ex) ؛ } // تدمير حبة المفرد التي تم إنشاؤها لتجنب استهلاك الموارد. تدمير beans () ؛ // إلغاء عملية التحديث وإعادة ضبط العلم النشط. CancelRefresh (ex) ؛ // نشر استثناء للمتصلب. رمي السابقين } أخيرًا {// إعادة تعيين ذاكرة التخزين المؤقت الأساسية لـ Spring's ResetCommonCaches () ؛ }}}بعد تحديث السياق
يوفر Spring Boot واجهتين للمستخدمين لتوسيع أنفسهم: ApplicationRunner و CommandLinerUnner. يمكنك تنفيذ بعض العمليات المشابهة لتهيئة البيانات بعد بدء تشغيل الحاوية (بعد تحديث السياق).
private void callrunners (ApplicationContext Context ، ApplicationArguments args) {list <Object> runners = new ArrayList <Object> () ؛ Runners.Addall (context.getBeansofType (ApplicationRunner.class) .values ()) anotationawareorderComparator.sort (Runners) ؛ // sorting for (Object Runner: New LinkedHashset <Object> (Runners)) {if (runner extlemor applicationRunner) {callrunner ((ApplicationRunner) ؛ }}}الاختلافان هما أن المعلمات مختلفة ، لذلك اختر بنفسك وفقًا للوضع الفعلي.
واجهة عامة CommandLinerUnner {void Run (String ... args) يلقي الاستثناء ؛ } واجهة عامة ApplicationRunner {void Run (ApplicationArguments args) يلقي الاستثناء ؛ }معلمات التنفيذ في CommandLinerUnner هي المعلمات صفيف السلسلة [] تتم معالجة المعلمات في ApplicationRunner لتوفير بعض الطرق مثل:
قائمة <Tring> getOptionValues (اسم السلسلة) ؛
احصل على قائمة القيمة وفقًا للاسم ، في أمر بدء تشغيل Java -foo = bar -foo = baz ، ثم قائمة الإرجاع ["BAR" ، "Baz"] وفقًا لاسم معلمة FOO
وفقًا للتحليل السابق ، يمكن تقسيم عملية بدء تشغيل حاوية الربيع إلى جزأين:
1) التعليق التوضيحي للتنفيذ: مسح الفاصوليا تحت النطاق المحدد ، قم بتحميل الفاصوليا المقابلة لفئة التكوين التلقائي وتحميلها في حاوية IOC.
2) تم تشغيل springappliocation.run () في طريقة الرجل عبر springapplicationevent ، وهناك 6 فئات فرعية:
applicationfailedevent.classapplicationpreparedevent.classapplicationReadyEvent.ClassApplicationStartedEvent.classapplicationStartingevent.ClassSpringApplicationEvent.class
هنا نستخدم الطراز الكلاسيكي الذي يحركه الأحداث ، تذكرة الجوية: طراز الربيع الذي يحركه الأحداث ونموذج المراقب
مخطط الفصل هو كما يلي:
كما هو موضح في الصورة أعلاه ، فهو نموذج كلاسيكي يحركه الربيع ، بما في ذلك 3 أدوار: ناشر الأحداث والحدث والمستمع. المقابلة مع الربيع-بوت هو:
1.EventPublishingRunListener ، فإن هذه الفئة تغلف نشر الأحداث ،
2. SpringapplicationEvent هو حدث محدد في SPRING-BOOT (الأحداث الستة المذكورة أعلاه) ، ورثت من Applicationevent (محددة في الربيع)
3. 监听者spring-boot并没有实现针对上述6种事件的监听者(我没找到...), 这里用户可以自己实现监听者(上述6种事件)来注入spring boot容器启动流程,触发相应的事件。
例如:实现ApplicationListener<ApplicationReadyEvent>这个接口,在容器启动完毕时最后一步listener.finished时,如果启动没有异常,就会执行!可以做一些数据初始化之类的操作。
لخص
The above is the relevant knowledge about spring boot container startup introduced to you by the editor. آمل أن يكون ذلك مفيدًا لك. إذا كان لديك أي أسئلة ، فيرجى ترك رسالة لي وسوف يرد المحرر إليك في الوقت المناسب. شكرا جزيلا لدعمكم لموقع wulin.com!