注解是开发Spring Boot 应用首先会遇到的一个注解,该注解其实相当于 @Configuration, @EnableAutoConfiguration 和 @ComponentScan 三者的集合,可以说一种简化的写法。

一个常见的Spring Boot 的启动类如下(代码来至 课堂实验手册):

1
2
3
4
5
6
7
8
@SpringBootApplication
public class StarterApplication {

public static void main(String[] args) {
SpringApplication.run(StarterApplication.class, args);
}

}

从功能上来说:

@Configuration - 把启动类(StarterApplication)标记为配置类,因此可以在该类中使用@Bean注解来声明在Spring容器中使用的类实例。

@EnableAutoConfiguration - 允许自动配置。

@ComponentScan - 使用默认参数设置Spring 容器扫描Bean时的搜索路径。默认参数为搜索当前包及其子包。在案例中,因为 StarterApplication 位于包 cn.com.hohistar.tutorial.springboot.starter 中,如果不做任何改变,则只有在 cn.com.hohistar.tutorial.springboot.starter 包及其子包(api, biz, configuration, exception, model, repository)中的类能够被Spring 容器发现,实例化,装配,注入。

TAGS