Spring Boot 核心注解与配置文件

@SpringBootApplication注解

  Spring Boot项目有一个入口类 (*Application) 在这个类中有一个main 方法,是运行该项目的切入点。而@SpringBootApplication 注解就是作用在这个启动类上面的,它是Spring Boot 的核心注解,经过查看源码后,发现它其实是一个组合注解。

 1 @Target(ElementType.TYPE)
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Documented
 4 @Inherited
 5 @SpringBootConfiguration
 6 @EnableAutoConfiguration
 7 @ComponentScan(excludeFilters = { 
 8         @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
 9     @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
10 public @interface SpringBootApplication {        

  @SpringBootConfiguration:这是Spring Boot的配置注解,也是一个组合注解,与@Configuration作用相同,标识这是一个被装载的Bean,在Spring Boot项目中推荐使用       @SpringBootConfiguration替代@Configuration。                

1 @Target({ElementType.TYPE})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Configuration
5 public @interface SpringBootConfiguration {
6 }

  @EnableAutoConfiguration:启用自动配置的注解,使用它之后,Spring Boot会根据项目中依赖的jar包自动配置项目的配置项,比如:添加了spring-boot-starter-web的依赖,项目中也就会引入SpringMVC的依赖,并且Spring Boot会自动配置tomcat SpringMVC

  @ComponentScan:默认扫描@SpringBootApplication所在类的同级目录以及它的子目录,excludeFilters:指定不适合组件扫描的类型。

关闭自动配置

  Spring Boot会根据项目中的jar包依赖,自动做出配置,Spring Boot支持的自动配置非常多,致使它的初始化时间比较长,因此为了避免不必要的耗时,可以将一些和第三方组件的自动集成和配置关闭。比如不想自动配置Redis:

@SpringBootApplication(exclude = {RedisAutoConfiguration.class})

自定义Banner

  在启动Spring Boot 项目的时候在控制台上会输出一个SPRING 的图案。可以通过banner文件自定义这个图案,同时也可以关闭这个输出图案。

  自定义Banner~ 可以通过这个链接就可以自定义想要输出的图案,然后把自定义的图案拷贝到一个文件,将该文件命名为banner.txt 放到resources 目录中重启即可看到自定义的图案。

当然也可以关闭控制台输出团案:修改main 方法中的代码:

public static void main(String[] args) {
        //SpringApplication.run(SpringbootTestApplication.class, args);
        SpringApplication application = new SpringApplication(SpringbootTestApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }  

Spring Boot 核心配置文件

   Spring Boot 的核心配置文件是 applicationbootstrap 配置文件。

  application 配置文件主要用于 Spring Boot 项目的自动化配置。

  bootstrap 配置文件有以下几个应用场景。

  • 使用 Spring Cloud Config 配置中心时,这时需要在 bootstrap 配置文件中添加连接到配置中心的配置属性来加载外部配置中心的配置信息;
  • 一些固定的不能被覆盖的属性;
  • 一些加密/解密的场景;

而配置文件又有两种格式:.properties.yaml,它们的区别主要是书写格式不同。

.properties

spring.datasource.username=root

.yaml:

spring:
    datasource:
        username: root    

另外,.yaml 格式不支持 @PropertySource 注解导入配置。

导入XML配置文件

  SpringBoot提倡零配置,它经为我们做了很多的配置但是如果在相关的项目中仍然需要xml 文件做一些额外的配置,别担心,Spring Boot 也是支持的。可以在入口类通过@ImportResource 进行xml 配置文件的导入并且支持对多个xml 文件的配置。

@ImportResource({"classpath:*.xml","classpath:**.xml"})
原文地址:https://www.cnblogs.com/jie-y/p/11239258.html