
2.3 SpringBoot注解分析
通过前面的学习可以发现,在整个SpringBoot程序里面使用了许多注解,这些注解的作用如表2-1所示。
表2-1 SpringBoot注解

在给定的几个注解中,@EnableAutoConfiguration为整个SpringBoot的启动注解配置,也就是说,这个注解应该随着程序的主类一起进行定义。但是该注解有一个前提,就是只能够扫描在同一程序类包中的配置程序,很明显其功能是不足的。
对于控制器程序类,由于在项目中有许多的控制器,那么最好将这些类统一保存在一个包中(如将所有的控制器程序类保存在cn.mldn.mldnboot.controller中,这是cn.mldn.mldnboot子包),在这样的环境下建议开发者使用@SpringBootApplication注解实现启动配置。
注意:请严格遵守SpringBoot的自动配置约束。
在SpringBoot开发过程中,为了简化开发配置,往往会在SpringBoot启动类下创建若干个子包,这样子包中的注解就都可以自动扫描到(@EnableAutoConfiguration注解不支持此功能),并且可以实现依赖关系的自动配置。以本程序为例,如果要进行标准开发,则程序的开发包结构如图2-4所示。

图2-4 SpringBoot项目结构
此时保存在cn.mldn.mldnboot下的所有子包中配置的注解都可以被Spring容器自动扫描。如果不在指定的子包中,程序启动类就需要配置@ComponentScan注解设置扫描包。这样的配置会显得整个项目非常啰嗦,如果不是必须的情况下,不建议这样配置。
可以简单地将@SpringBootApplication理解为:@SpringBootApplication=@EnableAuto Configuration +@ComponentScan(扫描父包)。
1.【mldnboot-base项目】建立一个控制器类。

2.【mldnboot-base项目】编写程序启动类(SpringBootStartApplication),使用@SpringBootApplication进行注解。

由于启动程序类保存在cn.mldn.mldnboot父包下,所以该包中所有的子包都将被自动扫描,而后自动实现配置。