前言

在学习springboot中,有一些注解经常用到,本节就具体讲下常用的注解以及如何使用。

正文

@SpringBootApplication

springboot项目一般都会有一个*Application的入口类,入口类中会有一个main方法,这是一个标准的java应用程序的入口方法。入口类有一个核心的注解:@SpringBootApplication,来看一下截图:

Spring Boot常用注解

@SpringBootApplication是一个组合注解,又包含了多个注解,其中比较重要的注解有:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

@SpringBootConfiguration

@SpringBootConfiguration也是一个组合注解,如下图:

Spring Boot常用注解

可以看到我们熟悉的@Configuration。从Spring3.0 开始,@Configuration可以用于定义配置类,替换xml配置,被注解的类内部包含一个或多个@Bean注解方法。这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

在springboot项目中,推荐使用@SpringBootConfiguration代替@Configuration

@EnableAutoConfiguration

@EnableAutoConfiguration用于启用自动配置,该注解会根据添加的jar包自动配置项目的配置项,比如我们添加了spring-boot-starter-web,项目中就会引入springMvc的依赖,springboot就会自动配置tomcat和springMvc

Spring Boot常用注解

@ComponentScan

@ComponentScan会扫描指定路径下的的类,并将其加入到Ioc容器中。在springboot中,@ComponentScan默认扫描@SpringBootApplication所在类的同级目录以及它的子目录。

也可以使用@ComponentScan(basePackageClasses = com.qingtian.web.controller)来制定扫描包路径

附录

参考文档

源码和基础教程汇总

相关文章:

  • 2018-04-25
  • 2018-03-21
  • 2018-05-28
  • 2018-10-29
  • 2018-08-30
  • 2018-05-23
  • 2021-11-29
  • 2021-09-27
猜你喜欢
  • 2019-01-29
  • 2018-05-05
  • 2018-02-28
  • 2020-05-20
  • 2021-02-05
  • 2021-06-20
  • 2020-10-30
  • 2018-06-28
相关资源
相似解决方案