spring boot 启动类

做项目用到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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/399036.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

UIImageView圆角,自适应图片宽高比例,图片拉伸,缩放比例和图片缩微图

/* 设置圆角&#xff0c;通过layer中的cornerRadius和masksToBounds即可。 自适应图片宽高比例。通过UIViewContentModeScaleAspectFit设置&#xff0c;注意这个UIImageView的frame就不是init中的数据了。 同样的UIImage图片放入不同frame中的UIIma…

FlashFXP使用教程

点FlashFXP菜单栏“站点-站点管理”打开站点管理器。然后点新建站点&#xff0c;输入站点名称&#xff08;随意&#xff09;&#xff0c;确定。 编辑站点管理器里新建的站点的相关信息&#xff0c;包括站点名称、地址、用户名称、密码等。编辑完成&#xff0c;点应用保存站点信…

七 内置锁 wait notify notifyall; 显示锁 ReentrantLock

Object中对内置锁进行操作的一些方法&#xff1a; Java内置锁通过synchronized关键字使用&#xff0c;使用其修饰方法或者代码块&#xff0c;就能保证方法或者代码块以同步方式执行. 内置锁使用起来非常方便&#xff0c;不需要显式的获取和释放&#xff0c;任何一个对象都能作为…

php如何制定跳转到app原生页面,js实现界面向原生界面发消息并跳转功能

本文实例为大家分享了js界面向原生界面发消息并跳转的具体代码&#xff0c;供大家参考&#xff0c;具体内容如下步骤一在idea中&#xff0c;打开rn项目下的./Android/app,这个过程需要一点儿时间&#xff0c;可能还需要下载gradle的依赖什么的。步骤二跟做原生app没差&#xff…

apm固定翼调试方法

APM飞控传说是大神的神器新手的噩梦,APM是个便宜又好用的飞控~刚开始给我的天行者X5按APM飞控的时候也查询搜索了很多,参数值,修改和混控和混控量的修改翻遍了资料发现咱们论坛教程比较少,所以开帖总结一下本人在用apm玩固定翼一些经验给想玩apm飞控的模友们.如果有哪里说错哪里…

你的工作单位也需善待

善待这个词&#xff0c;常常和家人、朋友联系在一起&#xff0c;其实你不仅要善待家人和朋友&#xff0c;还要善待你所在的工作单位。单位给了你创造财富生存的机会&#xff0c;给了你发挥聪明才智的平台&#xff0c;给了你体现人生价值的天空&#xff0c;所以要善待它。在单位…

识别图片baidu ai php,PHP+百度AI OCR文字识别实现了图片的文字识别功能

第一步可定要获取百度的三个东西 要到百度AI网站(http://ai.baidu.com/)去注册 然后获得-const APP_ID 请填写你的appid;-const API_KEY 请填写你的API_KEY;-const SECRET_KEY 请填写你的SECRET_KEY;第二步下载SDK或者使用官方的 http://ai.baidu.com/sdk 下载第三步 然后就…

Leetcode: Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".What if the given tree could be any binary tree? Would your previous solution still work?Note:You may only use constant extra space. For example, Given the following binary tre…

深入理解javascript原型和闭包(4)——隐式原型

注意&#xff1a;本文不是javascript基础教程&#xff0c;如果你没有接触过原型的基本知识&#xff0c;应该先去了解一下&#xff0c;推荐看《javascript高级程序设计&#xff08;第三版&#xff09;》第6章&#xff1a;面向对象的程序设计。 上节已经提到&#xff0c;每个函数…

ecshop 手机版的php代码在哪里,PHP 在ecshop上集成 手机网页支付_php

参考alipay网页支付接口的代码其实原理跟ecshop上集成的alipay支付差不多 就是因为利用curl请求的时候相应时间过长 所以不能直接去先post数据再生成button/*** 生成支付代码* param array $order 订单信息* param array $payment 支付方式信息*/function get…

技术回归本位:海尔引领空调产业重构格局

当前&#xff0c;互联网新思维方式日趋侵染&#xff0c;越来越多的细分领域在“互联网”理念下纷纷尝试跨界探索新的创新&#xff0c;一些商家除了推出全新战略型产品和服务之外&#xff0c;还在主打营销概念争夺舆论风口方面投入了巨大的精力与资源。在这种以理念为中心的时代…

护肤

选择什么 护肤品 2222选择什么 1氨基酸洗面奶&#xff1a;去油控油能力适中&#xff0c;用完皮肤清爽&#xff0c;比较亲和&#xff0c;一般成分里多次出现“氨酸”这两个字的就是氨基酸洗面奶&#xff0c;这种洗面奶适合长期使用.</p><p><b>皀基洗面奶&…

与TCP/IP协议的初次见面(一)

引言 最近LZ有了一点时间&#xff0c;于是便拿出TCP/IP的书本开始啃。开始的时候&#xff0c;啃起来枯燥无味&#xff0c;现在好不容易有点开窍&#xff0c;于是赶忙记录一下&#xff0c;生怕自己一转眼就给忘了。不过计算机系统原理就有点可惜了&#xff0c;最近一直没时间看&…

Oracle约数,Oracle约束简介

整理自《OCP认证指南》001 概述表约束是数据库能够实施业务规则以及保证数据遵循实体——关系模型的一种手段&#xff0c;其中&#xff0c;实体——关系模型由定义应用程序数据结构的系统分析所确定。在针对定义了约束的表执行任何DML时&#xff0c;如果DML违反了约束&#xff…

用cmd运行java可以javac不行(win10)

今天发现个有趣的问题&#xff0c;用cmd运行java可以javac不行。(win10) java-home和classpath配置没有问题,最后发现问提出先在path&#xff0c;在这里看并没有异常。 在上面图片中点击编辑文本&#xff0c;在这里可以清楚的看见多了引号和分号&#xff0c;将其删除&#xff0…

vs窗体 oracle,VS2010连接oracle数据库的简单例子

下面附有代码&#xff1a;using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.OracleClient;namespace 连接oracle数据库…

EasyUI实现两个列表联动

开发中会遇到如下界面的功能样式&#xff1a; 点击左边列表记录时&#xff0c;右边的列表显示所属分类的数据 实现方法&#xff1a; 1、首先绑定左侧列表的OnClickRow事件&#xff0c;方法为&#xff1a;getDetail. 如下代码所示。 <table id"dg" class"easy…

CodeForces 176A Trading Business 贪心

Trading Business题目连接&#xff1a; http://codeforces.com/problemset/problem/176/A Description To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anythi…

Docker快速入门实践-纯干货文章

Docker快速入门实践-老男孩高级架构师课程内容&#xff0c;如果细看还能发现讲解视频呦&#xff01;小伙伴们赶紧猛戳吧&#xff01;老男孩高级架构师内部学员实践文档分享&#xff01;Docker快速入门实践-纯干货文章老男孩教育2016启用最新的官方博文地址&#xff1a;http://b…

180102

https://pan.baidu.com/s/1nvqYFt3转载于:https://www.cnblogs.com/wjy123/p/8175593.html