做项目用到spring boot 感觉spring boot用起来比较流畅。想总结一下,别的不多说,从入口开始。

spring boot启动类Application.class 不能直接放在main/java文件夹下

一、spring boot的入口启动类概览。

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;@SpringBootApplication
@EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class)
@EnableScheduling
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}/** * 跨域过滤器 * @return CorsFilter 跨域过滤器对象*/  @Bean  public CorsFilter corsFilter() {  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  source.registerCorsConfiguration("/**", buildConfig()); // 4  return new CorsFilter(source);  }     private CorsConfiguration buildConfig() {  CorsConfiguration corsConfiguration = new CorsConfiguration();  corsConfiguration.addAllowedOrigin("*");  corsConfiguration.addAllowedHeader("*");  corsConfiguration.addAllowedMethod("*");  return corsConfiguration;  }
}

 二、spring boot的入口启动类详细解释

飞过导入代码不看,我们先看第一部分:

  • @SpringBootApplication
  • @EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class)    配置
  • @EnableScheduling                从应用的全局定义一个调度器

@SpringBootApplication   是什么?@EnableAutoConfiguration   又是什么? 记住一句话:学习很简单,动手玩一玩,要是还不懂,再问1、2、3。

好吧,我们就进去玩一玩,点击进去就以看到源码。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {/*** Exclude specific auto-configuration classes such that they will never be applied.* @return the classes to exclude*/Class<?>[] exclude() default {};/*** Exclude specific auto-configuration class names such that they will never be* applied.* @return the class names to exclude* @since 1.3.0*/String[] excludeName() default {};/*** Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}* for a type-safe alternative to String-based package names.* @return base packages to scan* @since 1.3.0*/@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")String[] scanBasePackages() default {};/*** Type-safe alternative to {@link #scanBasePackages} for specifying the packages to* scan for annotated components. The package of each class specified will be scanned.* <p>* Consider creating a special no-op marker class or interface in each package that* serves no purpose other than being referenced by this attribute.* @return base packages to scan* @since 1.3.0*/@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")Class<?>[] scanBasePackageClasses() default {};}

从源代码中可以看到 @SpringBootApplication 被 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 注解所修饰。

再深入的玩一下 @SpringBootConfiguration 注意其中的一句话:就是下文中的红色部分。 Can be used as an alternative to the Spring's * standard {@code @Configuration} annotation so that configuration can be found * automatically (for example in tests).
/*** Indicates that a class provides Spring Boot application* {@link Configuration @Configuration}. Can be used as an alternative to the Spring's* standard {@code @Configuration} annotation so that configuration can be found* automatically (for example in tests).
 * <p>* Application should only ever include <em>one</em>* {@code @SpringApplicationConfiguration} and most idiomatic Spring Boot applications* will inherit it from {@code @SpringBootApplication}.** @author Phillip Webb* @since 1.4.0*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {}

 

这就是说,@SpringBootConfiguration是作为 原来Spring 注解体系中@Configuration 注解的替代品出现的, @SpringBootConfiguration是@Configuration 的壳。储君上位成了国王,换上丞相的儿子做丞相,其它官位不变;甚至连儿子都算不上,顶多是给老丞相新定做了一身衣服。

@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan

@Configuration、                  @EnableAutoConfiguration、@ComponentScan

总结: Springboot 提供了统一的注解@SpringBootApplication 来替代以上三个注解,简化程序的配置。下面解释一下各注解的功能。

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

关于@Target、@Retention、@Documented等注释 可以参照(http://blog.csdn.net/bluetjs/article/details/52250596)自行脑补。

哎呀还是再开一篇来讲吧。

spring boot 提倡约定优于配置,方便之处就是用约定来代替配置,减少的是手工配置不等于去掉配置。

凡是遇到注解我们都要问一句:那原来的配置是什么样子?现在的约定是什么样子? 好吧,

@Configuration

原来是这个样子:

<beans xmlns="http://www.springframework.org/schema/beans" ... ...></beans>

现在:

@Configuration

@EnableAutoConfiguration

顾名思义,@EnableAutoConguration是自动化配置。那就是@Configuration的高级形式,其本质不变的就是,最终形成的配置放在 beans内部,和@Bean的效果相同。不过它的适用范围大部分是内部默认包。也就是它对这些Bean的有特殊要求。

 1 @Target(ElementType.TYPE)
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Documented
 4 @Inherited
 5 @AutoConfigurationPackage
 6 @Import(EnableAutoConfigurationImportSelector.class)
 7 public @interface EnableAutoConfiguration {
 8
 9     String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
10
11     /**
12      * Exclude specific auto-configuration classes such that they will never be applied.
13      * @return the classes to exclude
14      */
15     Class<?>[] exclude() default {};
16
17     /**
18      * Exclude specific auto-configuration class names such that they will never be
19      * applied.
20      * @return the class names to exclude
21      * @since 1.3.0
22      */
23     String[] excludeName() default {};
24
25 }

EnableAutoConfigurationImportSelector.Class
public String[] selectImports(AnnotationMetadata metadata) {try {AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(EnableAutoConfiguration.class.getName(),true));Assert.notNull(attributes, "No auto-configuration attributes found. Is "+ metadata.getClassName()+ " annotated with @EnableAutoConfiguration?");// Find all possible auto configuration classes, filtering duplicatesList<String> factories = new ArrayList<String>(new LinkedHashSet<String>(SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,this.beanClassLoader)));// Remove those specifically disabledfactories.removeAll(Arrays.asList(attributes.getStringArray("exclude")));// Sortfactories = new AutoConfigurationSorter(this.resourceLoader).getInPriorityOrder(factories);return factories.toArray(new String[factories.size()]);}catch (IOException ex) {throw new IllegalStateException(ex);}}

获取类路径下spring.factories下key为EnableAutoConfiguration全限定名对应值

@AutoConfigurationPackage

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {}

@Import

每当我看到这个注释,意味着我快触摸到问题所在。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {/*** {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}* or regular component classes to import.*/Class<?>[] value();}

@ComponentScan

我们知道Spring Boot默认会扫描启动类同包以及子包下的注解,实现的途径就是必须在启动类引入注解@ComponetScan。

可以看到,项目中引入了注解@SpringBootApplication 这就意味(本质上)引入注解@ComponetScan,所以就会扫描Application.Class所在包以及子包的注解。

当然,如果你要改变这种扫描包的方式,原理很简单就是:用@ComponentScan注解进行指定要扫描的包以及要扫描的类。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {

}

注解:@ComponentScan的内容:

知识点:

@ComponentScan has a Annotation @Repeatable with has a vale of ComponentScans.class
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ComponentScans {ComponentScan[] value();}

知识点:

@Repeatable :indicate that the annotation type whose declaration it
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {/*** Indicates the <em>containing annotation type</em> for the* repeatable annotation type.* @return the containing annotation type*/Class<? extends Annotation> value();
}


知识点:

@Retention:specify Annotation retention policy such as SOURCE、CLASS、RUNTIME
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {/*** Returns the retention policy.* @return the retention policy*/RetentionPolicy value();
}

接下来看代码

     /** * 跨域过滤器 * @return  CorsFilter */  @Bean  public CorsFilter corsFilter() {  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  source.registerCorsConfiguration("/**", buildConfig()); // 4  return new CorsFilter(source);  }

@Bean

原来

<bean id = "corsFilter" class="org.springframework.web.filter.CorsFilter"> </bean> 

@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象。

在这个类中涉及到的配置就是:

<beans xmlns="http://www.springframework.org/schema/beans"  ... ...    ><bean id = "corsFilter" class="org.springframework.web.filter.CorsFilter"></bean></beans>

@EnableScheduling

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)
@Documented
public @interface EnableScheduling {}

@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class SchedulingConfiguration {@Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)@Role(BeanDefinition.ROLE_INFRASTRUCTURE)public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {return new ScheduledAnnotationBeanPostProcessor();}}

忍不住要插点小常识:
大概说一下:
Spring 是一个“引擎”
Spring MVC 是基于 Spring 的一个 MVC 框架
Spring Boot 是基于 Spring4 的条件注册的一套快速开发整合包

Spring 最初利用“工厂模式”( DI )和“代理模式”( AOP )解耦应用组件,并构建了一些列功能组件。大家觉得挺好用,于是按照 MVC 框架模式,(用Spring 解耦的组件)搞了一个MVC用来开发 web 应用也就是( SpringMVC )。然后有发现每次开发都要搞很多依赖,写很多样板代码很麻烦,于是搞了一些懒人整合包( starter ),这套就是 Spring Boot 。 
spring 框架有超多的延伸产品例如 boot security jpa etc... 但它的基础就是 spring 的 ioc 和 aop ioc 提供了依赖注入的容器 aop 解决了面向横切面的编程 然后在此两者的基础上实现了其他延伸产品的高级功能 Spring MVC 呢是基于 Servlet 的一个 MVC 框架 主要解决 WEB 开发的问题 因为 Spring 的配置太复杂了 各种 XML JavaConfig hin 麻烦 于是懒人改变世界推出了 Spring boot 约定优于配置 简化了 spring 的配置流程 简单谈下自己的理解   以上来自度娘,感觉和自己的理解相当。直接拿来用,占个坑。以后完善。

 springApplication可以读取不同种类的源文件:

  • 类- java类由AnnotatedBeanDefinitionReader加载。
  • Resource - xml资源文件由XmlBeanDefinitionReader读取, 或者groovy脚本由GroovyBeanDefinitionReader读取
  • Package - java包文件由ClassPathBeanDefinitionScanner扫描读取。
  • CharSequence - 字符序列可以是类名、资源文件、包名,根据不同方式加载。如果一个字符序列不可以解析程序到类,也不可以解析到资源文件,那么就认为它是一个包。
  • http://www.51drhome.com
  • http://www.sohu.com/a/157811214_405968
  • http://www.wang1314.com/doc/topic-2664759-1.html
  • http://jianfangmi.com/qinggangbieshu/qinggangbieshuanli/201612/00001662.html

转载于:https://www.cnblogs.com/huangsxj/p/7728123.html

spring boot 启动类相关推荐

  1. spring boot启动类启动 错误: 找不到或无法加载主类 xxx.xxxx.Application 的解决方法

    spring boot启动类启动 错误: 找不到或无法加载主类 xxx.xxxx.Application 的解决方法 导入的一个外部的spring boot项目,运行启动类,忽然提示找不到或者无法加载 ...

  2. Spring boot 启动后执行特定的操作

    有时候我们需要在应用启动完成后执行一些特定的操作,比如: 删除一些临时文件或者Redis中的缓存 将一些字典类的数据加载到缓存,这样就不用每次去数据库中查了,有些关联数据从缓存中取得赋值就可以了,不再 ...

  3. Spring Boot启动过程源码分析--转

    https://blog.csdn.net/dm_vincent/article/details/76735888 关于Spring Boot,已经有很多介绍其如何使用的文章了,本文从源代码(基于Sp ...

  4. Spring Boot 启动载入数据 CommandLineRunner

    Spring Boot 启动载入数据 CommandLineRunner 实际应用中,我们会有在项目服务启动的时候就去载入一些数据或做一些事情这种需求. 为了解决这种问题.Spring Boot 为我 ...

  5. 在Spring Boot启动时运行代码

    Spring Boot会自动为我们执行很多配置,但是迟早您将不得不做一些自定义工作. 在本文中,您将学习如何进入应用程序引导生命周期并在Spring Boot启动时执行代码 . 因此,让我们看看该框架 ...

  6. Spring Boot————Spring Boot启动流程分析

    一.引言 Spring Boot 的启动虽然仅仅是执行了一个main方法,但实际上,运行流程还是比较复杂的,其中包含几个非常重要的事件回调机制.在实际生产开发中,有时候也会利用这些启动流程中的回调机制 ...

  7. 强大的Spring Boot启动监听器事件-初始化系统账号密码

    文章目录 前言 一.SpringApplicationEvents 事件类型 1.1 ApplicationStartingEvent 1.2 ApplicationEnvironmentPrepar ...

  8. [Spring Boot] 2. Spring Boot 启动过程定制化

    在上一篇文章中,从源码角度介绍了Spring Boot的启动过程.启动的代码虽然只有短短的一行,但是背后所做的工作还真不少,其中有一些可以定制化的部分,主要分为以下几个方面: 初始化器(Initial ...

  9. spring boot启动 Failed to scan from classloader hierarchy 解决方案

    文章目录 错误如下 : 原由 第一次修改 二次改造如下: 错误如下 : 15:01:57.051 [restartedMain] WARN o.a.t.util.scan.StandardJarSca ...

最新文章

  1. 奥鹏20春在线作业c语言,电子科20春《C语言(专科)》在线作业3答案
  2. Linux系统下启动MySQL的命令及相关知识
  3. Jira中的BUG导出
  4. 理解SQL Server中索引的概念,原理
  5. 【转】见与不见————仓央嘉措
  6. texlive 2022安装与使用
  7. 登录Unity官方商店时提示Sorry, this link is no longer valid.(此链接已失效)
  8. java之Io-File类
  9. 计算机 及其 应用系统
  10. 智源社区周刊:Gary Marcus谈大模型研究可借鉴的三个因素;OpenAI提出视频预训练模型VPT,可玩MC游戏...
  11. window location href is not a function错误解决
  12. 如何保障微服务架构下的数据一致性
  13. (二)Semi-supervised(半监督学习)李宏毅
  14. js中特殊字符以及转义
  15. paramiko.ssh_exception.SSHexception:Server connection dropped:
  16. 冯大辉Twitter每日推荐一位推友计划推友列表
  17. Gearman 心得
  18. #VCS# 关于Verdi KDB 数据库
  19. iOS ffmpeg+OpenGL播放yuv+openAL 快放 慢放 视频播放器
  20. [GMOJ]水叮当的舞步 From lydrainbowcat

热门文章

  1. 33条C#、.Net经典面试题目及答案
  2. du命令、df命令用法
  3. C#学习笔记四: C#3.0自动属性匿名属性及扩展方法
  4. 企业日志分析 五大问题需重点注意
  5. iOS-数据持久化-第三方框架FMDB的使用
  6. WPF的样式(Style)继承
  7. 关于Oracle实时数据库的优化思路
  8. SDUT-2121_数据结构实验之链表六:有序链表的建立
  9. 华为产品技术学习笔记之路由原理(一)
  10. 老王学linux-ftp