深入学习Springboot的注解@SpringBootApplication

你好我是辰兮,很高兴你能来阅读,本篇文章是关于Springboot注解的学习,另外补充了一点Springboot的启动方式小结,总结下来,分享获取新知,大家一起进步。



一、初识注解

最近在哔哩哔哩上面看Java面试会经常看到:说一说你对@SpringBootApplication这个注解的理解?
在这里插入图片描述

接下来带大家一起学习了解一下这个注解


@SpringBootApplication是一个组合注解,用于快捷配置启动类。

@SpringBootApplication包含的三个注解及其含义:

  • @Configuration: 用于定义一个配置类
  • @EnableAutoConfiguration :Spring Boot会自动根据你jar包的依赖来自动配置项目。
  • @ComponentScan: 告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。

自动配置、组件扫描,并能够在他们的“应用程序类”上定义额外的配置,可以使用一个@SpringBootApplication注解来启用这三个特性。


二、源码学习

点击打开@SpringBootApplication的源码看看

@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 {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};

    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

1、@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。

2、@EnableAutoConfiguration:是spring boot的核心功能,自动配置。这个注释告诉SpringBoot“猜”你将如何想配置Spring,基于你已经添加jar依赖项。如果spring-boot-starter-web已经添加Tomcat和Spring MVC,这个注释自动将假设您正在开发一个web应用程序并添加相应的spring设置.

通常推荐将 @EnableAutoConfiguration 配置在 root 包下,这样所有的子包、类都可以被查找到。

3、@ComponentScan : 通俗的讲,@ComponentScan 注解会自动扫描指定包下的全部标有 @Component注解 的类,并注册成bean,当然包括 @Component 下的子注解@Service、@Repository、@Controller。@ComponentScan 注解没有类似 、的属性


SpringBootApplication继承了以上三个注解,可以简化开发,是开发着注重业务。

如在之前扫描注解时,有spring ,springmvc 两个扫描,导致有两个bean容器,容易出现错误,现在他们都交给了springboot,容器就只有一个,冲突就不会出现了。


三、Springboot的启动方式

偶尔面试官也会考到为有几种启动Springboot项目的方式 其实有一些 最主要是三种

spring-boot的启动方式主要有三种:

1. 运行带有main方法类

2. 通过命令行 java -jar 的方式

3. 通过spring-boot-plugin的方式


1. 最简单的方法是运行带有main方法类

在这里插入图片描述
然后我们访问一下测试
在这里插入图片描述


2.通过java -jar的方式

使用mvn install先编译,在使用java -jar xxxxxxxxxx.jar启动

在项目当前目录进行编译,然后 进入target目录下,使用java命令启动


3.使用mvn spring-boot:run命令启动

首先我们的项目中有如下的插件

在这里插入图片描述
进入项目当前目录,然后使用命令
在这里插入图片描述
然后项目就启动了。


4.打包war包,丢到tomcat启动

5.使用docker容器等等…

未完待续


Java面试Offer直通车


The best investment is to invest in yourself

在这里插入图片描述

2020.06.14 记录辰兮的第82篇博客

猜你喜欢

转载自blog.csdn.net/weixin_45393094/article/details/106732844