一 点睛
先看下面这段代码
@RestController
@SpringBootApplication
public class Ch522Application {
@RequestMapping("/")
String index() {
return "Hello Spring Boot";
//return "book name is:" + bookName + " and book author is:" + bookAuthor;
}
public static void main(String[] args) {
SpringApplication.run(Ch522Application.class, args);
}
}
这段代码可以分析出以下内容:
1 Spring Boot通常有一个名为*Application的入口类,入口类有一个main方法,这个main方法就是一个标准的Java应用的入口方法。
2 在main方法中使用 SpringApplication.run(XXXApplication.class, args),启动Spring Boot应用项目。
二 赏析@SpringBootApplication源码
1 源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
/**
* Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
* for a type-safe alternative to String-based package names.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
/**
* Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
* scan for annotated components. The package of each class specified will be scanned.
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
}
2 解读
@SpringBootApplication注解组合了@Configuration、@EnableAutoConfiguration、@ComponentScan这三个注解;若不使用@SpringBootApplication注解,则可以在入口类上直接使用@Configuration、@EnableAutoConfiguration、@ComponentScan这三个注解。
@EnableAutoConfiguration让Spring Boot根据类路径的jar包依赖为当前项目进行自动化配置。
例如,添加了spring-boot-starter-web依赖,会自动添加Tomcat和Spring MVC的依赖,那么Spring Boot会对Tomcat和Spring MVC进行自动配置。
又如,添加了spring-boot-starter-data-jpa依赖,Spring Boot会自动进行JPA相关的配置。
Spring Boot会自动扫描@SpringBootApplication所在类同级包以及下级包里的Bean。建议入口类放置的位置在groupId+arctifactID组合的包名下。
关闭特定自动配置应该使用@SpringBootApplication注解的exclude参数,例如
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})