Spring Boot常用注解
前言
在学习springboot中,有一些注解经常用到,本节就具体讲下常用的注解以及如何使用。
正文
@SpringBootApplication
springboot项目一般都会有一个*Application的入口类,入口类中会有一个main方法,这是一个标准的java应用程序的入口方法。入口类有一个核心的注解:@SpringBootApplication
,来看一下截图:
@SpringBootApplication
是一个组合注解,又包含了多个注解,其中比较重要的注解有:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
@SpringBootConfiguration
@SpringBootConfiguration也是一个组合注解,如下图:
可以看到我们熟悉的@Configuration。从Spring3.0 开始,@Configuration可以用于定义配置类,替换xml配置,被注解的类内部包含一个或多个@Bean注解方法。这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
在springboot项目中,推荐使用@SpringBootConfiguration代替@Configuration
@EnableAutoConfiguration
@EnableAutoConfiguration用于启用自动配置,该注解会根据添加的jar包自动配置项目的配置项,比如我们添加了spring-boot-starter-web,项目中就会引入springMvc的依赖,springboot就会自动配置tomcat和springMvc
@ComponentScan
@ComponentScan会扫描指定路径下的的类,并将其加入到Ioc容器中。在springboot中,@ComponentScan默认扫描@SpringBootApplication所在类的同级目录以及它的子目录。
也可以使用@ComponentScan(basePackageClasses = com.qingtian.web.controller)
来制定扫描包路径
附录
参考文档
- spring-context-annotation:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/
- spring-boot-doc:https://docs.spring.io/spring-boot/docs/
源码和基础教程汇总
- springboot基础教程传送门:https://blog.****.net/qingtian_1993/article/details/80294369
- 项目源码,欢迎star:https://github.com/mcrwayfun/spring-boot-learning