SpringBoot核心注解原理java
今天跟你们来探讨下SpringBoot的核心注解@SpringBootApplication以及run方法,理解下springBoot为何不须要XML,达到零配置git
首先咱们先来看段代码github
@SpringBootApplication public class StartEurekaApplication { public static void main(String[] args) { SpringApplication.run(StartEurekaApplication.class, args); } }
咱们点进@SpringBootApplication来看web
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { }
上面的元注解咱们在这里不在作解释,相信你们在开发当中确定知道,咱们要来讲@SpringBootConfiguration @EnableAutoConfiguration 这两个注解,到这里咱们知道 SpringBootApplication注解里除了元注解,咱们能够看到又是@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan的组合注解,官网上也有详细说明,那咱们如今把目光投向这三个注解。redis
首先咱们先来看 @SpringBootConfiguration,那咱们点进来看spring
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration { }
咱们能够看到这个注解除了元注解之外,就只有一个@Configuration,那也就是说这个注解至关于@Configuration,因此这两个注解做用是同样的,那他是干吗的呢,相信不少人都知道,它是让咱们可以去注册一些额外的Bean,而且导入一些额外的配置。那@Configuration还有一个做用就是把该类变成一个配置类,不须要额外的XML进行配置。因此@SpringBootConfiguration就至关于@Configuration。tomcat
那咱们继续来看下一个@EnableAutoConfiguration,这个注解官网说是 让Spring自动去进行一些配置,那咱们点进来看springboot
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(EnableAutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { }
能够看到它是由 @AutoConfigurationPackage,@Import(EnableAutoConfigurationImportSelector.class)这两个而组成的,咱们先说@AutoConfigurationPackage,他是说:让包中的类以及子包中的类可以被自动扫描到spring容器中。 咱们来看@Import(EnableAutoConfigurationImportSelector.class)这个是核心,以前咱们说自动配置,那他到底帮咱们配置了什么,怎么配置的?就和@Import(EnableAutoConfigurationImportSelector.class)息息相关,程序中默认使用的类就自动帮咱们找到。咱们来看EnableAutoConfigurationImportSelector.classapp
public class EnableAutoConfigurationImportSelector extends AutoConfigurationImportSelector { @Override protected boolean isEnabled(AnnotationMetadata metadata) { if (getClass().equals(EnableAutoConfigurationImportSelector.class)) { return getEnvironment().getProperty( EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, true); } return true; } }
能够看到他继承了AutoConfigurationImportSelector咱们继续来看AutoConfigurationImportSelector,这个类有一个方法less
public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return NO_IMPORTS; } try { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); configurations = sort(configurations, autoConfigurationMetadata); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return configurations.toArray(new String[configurations.size()]); } catch (IOException ex) { throw new IllegalStateException(ex); } }
这个类会帮你扫描那些类自动去添加到程序当中。咱们能够看到getCandidateConfigurations()这个方法,他的做用就是引入系统已经加载好的一些类,究竟是那些类呢,咱们点进去看一下
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }
这个类回去寻找的一个目录为META-INF/spring.factories,也就是说他帮你加载让你去使用也就是在这个META-INF/spring.factories目录装配的,他在哪里?
咱们点进spring.factories来看
咱们能够发现帮咱们配置了不少类的全路径,好比你想整合activemq,或者说Servlet
能够看到他都已经帮咱们引入了进来,我看随便拿几个来看
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
好比咱们常常用的security,能够看到已经帮你配置好,因此咱们的EnableAutoConfiguration主要做用就是让你自动去配置,但并非全部都是建立好的,是根据你程序去进行决定。 那咱们继续来看
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
这个注解你们应该都不陌生,扫描包,放入spring容器,那他在springboot当中作了什么策略呢?咱们能够点跟烟去思考,帮咱们作了一个排除策略,他在这里结合SpringBootConfiguration去使用,为何是排除,由于不可能一上来所有加载,由于内存有限。
那么咱们来总结下@SpringbootApplication:就是说,他已经把不少东西准备好,具体是否使用取决于咱们的程序或者说配置,那咱们到底用不用?那咱们继续来看一行代码
public static void main(String[] args) { SpringApplication.run(StartEurekaApplication.class, args); }
那们来看下在执行run方法到底有没有用到哪些自动配置的东西,好比说内置的Tomcat,那咱们来找找内置Tomcat,咱们点进run
public static ConfigurableApplicationContext run(Object[] sources, String[] args) { return new SpringApplication(sources).run(args); }
而后他调用又一个run方法,咱们点进来看
public ConfigurableApplicationContext run(String... args) { //计时器 StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; configureHeadlessProperty(); //监听器 SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); Banner printedBanner = printBanner(environment); //准备上下文 context = createApplicationContext(); analyzers = new FailureAnalyzers(context); //预刷新context prepareContext(context, environment, listeners, applicationArguments, printedBanner); //刷新context refreshContext(context); //刷新以后的context afterRefresh(context, applicationArguments); listeners.finished(context, null); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } return context; } catch (Throwable ex) { handleRunFailure(context, listeners, analyzers, ex); throw new IllegalStateException(ex); } }
那咱们关注的就是 refreshContext(context); 刷新context,咱们点进来看
private void refreshContext(ConfigurableApplicationContext context) { refresh(context); if (this.registerShutdownHook) { try { context.registerShutdownHook(); } catch (AccessControlException ex) { // Not allowed in some environments. } } }
咱们继续点进refresh(context);
protected void refresh(ApplicationContext applicationContext) { Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext); ((AbstractApplicationContext) applicationContext).refresh(); }
他会调用 ((AbstractApplicationContext) applicationContext).refresh();方法,咱们点进来看
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
这点代码似曾相识啊 没错,就是一个spring的bean的加载过程我在,解析springIOC加载过程的时候介绍过这里面的方法,若是你看过Spring源码的话 ,应该知道这些方法都是作什么的。如今咱们不关心其余的,咱们来看一个方法叫作 onRefresh();方法
protected void onRefresh() throws BeansException { // For subclasses: do nothing by default. }
他在这里并无实现,可是咱们找他的其余实现,咱们来找
咱们既然要找Tomcat那就确定跟web有关,咱们能够看到有个ServletWebServerApplicationContext
@Override protected void onRefresh() { super.onRefresh(); try { createWebServer(); } catch (Throwable ex) { throw new ApplicationContextException("Unable to start web server", ex); } }
咱们能够看到有一个createWebServer();方法他是建立web容器的,而Tomcat不就是web容器,那他是怎么建立的呢,咱们继续看
private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = getServletContext(); if (webServer == null && servletContext == null) { ServletWebServerFactory factory = getWebServerFactory(); this.webServer = factory.getWebServer(getSelfInitializer()); } else if (servletContext != null) { try { getSelfInitializer().onStartup(servletContext); } catch (ServletException ex) { throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); }
factory.getWebServer(getSelfInitializer());他是经过工厂的方式建立的
public interface ServletWebServerFactory { WebServer getWebServer(ServletContextInitializer... initializers); }
能够看到 它是一个接口,为何会是接口。由于咱们不止是Tomcat一种web容器。
咱们看到还有Jetty,那咱们来看TomcatServletWebServerFactory
@Override public WebServer getWebServer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); }
那这块代码,就是咱们要寻找的内置Tomcat,在这个过程中,咱们能够看到建立Tomcat的一个流程。由于run方法里面加载的东西不少,因此今天就浅谈到这里。若是不明白的话, 咱们在用另外一种方式来理解下,你们要应该都知道stater举点例子
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
因此咱们不防不定义一个stater来理解下,咱们作一个需求,就是定制化不一样的人跟你们说大家好,咱们来看
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> </parent> <groupId>com.zgw</groupId> <artifactId>gw-spring-boot-srater</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> </dependencies>
咱们先来看maven配置写入版本号,若是自定义一个stater的话必须依赖spring-boot-autoconfigure这个包,咱们先看下项目目录
public class GwServiceImpl implements GwService{ @Autowired GwProperties properties; @Override public void Hello() { String name=properties.getName(); System.out.println(name+"说:大家好啊"); } }
咱们作的就是经过配置文件来定制name这个是具体实现,
@Component @ConfigurationProperties(prefix = "spring.gwname") public class GwProperties { String name="zgw"; public String getName() { return name; } public void setName(String name) { this.name = name; } }
这个类能够经过@ConfigurationProperties读取配置文件
@Configuration @ConditionalOnClass(GwService.class) //扫描类 @EnableConfigurationProperties(GwProperties.class) //让配置类生效 public class GwAutoConfiguration { /** * 功能描述 托管给spring * @author zgw * @return */ @Bean @ConditionalOnMissingBean public GwService gwService() { return new GwServiceImpl(); } }
这个为配置类,为何这么写由于,spring-boot的stater都是这么写的,咱们能够参照他仿写stater,以达到自动配置的目的,而后咱们在经过spring.factories也来进行配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.gw.GwAutoConfiguration
而后这样一个简单的stater就完成了,而后能够进行maven的打包,在其余项目引入就可使用,在这里列出代码地址
https://github.com/zgw1469039806/gwspringbootsrater
到此本文结束,欢迎转载,请标注出处和做者,谢谢!