Spring-boot经典布局
先阶段基于Spring-boot的开发一般都遵循这个经典布局。
- Spring-boot 项目,都有一个主应用类
通常建议您将主应用类定位到其它类之上的根包中,位置一般就是经典布局的Application.java(例子中为StartUp.java)
@SpringBootApplication
public class StartUp extends WebMvcConfigurerAdapter
{
public static void main(String[] args) throws Exception
{
SpringApplication.run(StartUp.class, args);
}
}
@SpringBootApplication 完成了三个任务,
@EnableAutoConfiguration,
@ComponentScan。
@SpringBootConfiguration
a) @EnableAutoConfiguration 表示,在启动的时候根据你已经添加jar依赖项,假设你开发的框架,并为你添加相应的Spring配置。例如spring-boot-starter-web已经添加Tomcat和Spring MVC,这个注释自动将假设您正在开发一个web应用程序并添加相应的spring设置。
b) @Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean
c) @ComponentScan,按照布局,逐个扫描包,自动扫描所有的Spring组件(@Entity,@Controller,@Service,@Component等),包括 @Configuration 类。
3. properties 文件使用
a) Spring-boot使用properties文件需要编译的时候放在pom <build> 下的<resources>指定的resource路径下路径,如果不指定,则不加载。
b) Spring-boot 支持多环境配置。在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中 {profile}对应你的环境标识,
比如:application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境
至于哪个具体的配置文件会被加载,需要在application.properties文件中通过 spring.profiles.active属性来设置,其值对应{profile}值。
c) 启动的时候 读取application.properties内容来判断,是否有spring.profiles.active来指定导入的 配置。这时代码中无法读取application.properties中的配置。
application.properties中配置通用内容,并设置spring.profiles.active=dev,以开发环境为默认配置
application-{profile}.properties中配置各个环境不同的内容
通过命令行方式去激活不同环境的配置
4.测试使用的Spring–boot格式