1. @SpringBootApplication 注解
- 这个注解相当于三个注解的功能集成
- 默认的包结构及其作用
- 主程序 Application.java 放在根包,在其他类之上。
@SpringBootApplication
注解写在主程序上。- Spring 对类的扫描默认仅涵盖主程序所在的包及子包。
3. 零 Spring 配置文件
- SpringBoot 中建议放弃通过 XML 定义 Spring 应用程序,推荐在代码类上面通过
@Configuration
实现配置。 - 如有需要,还可以通过
@ImportResource
来导入 xml 配置文件。
- 注:要使
@Configuration
生效,你需要将他写在 SpringBoot 入口程序上面,或者使用@EnableAutoConfiguration
或@SpringBootApplication
这两个注解来开启自动加载功能。4. 个性化加载配置
5. 外部参数配置信息加载
Spring 应用程序可以通过属性文件、YAML 文件、环境变量和命令行参数等方式的外部化参数配置。
- 启动时命令行传参:
java -jar app.jar --name="test"
。- e.g.
java -jar app.jar --spring.profiles.active=dev
- e.g.
- SpringBoot 配置信息中的特殊值:
SPRING_APPLICATION_JSON='{"name":"test"}'
。- e.g.
java -jar app.jar --SPRING_APPLICATION_JSON=\"{\"spring.profiles.active\":\"dev\"}\"
- e.g.
- 如果是 Web 应用,可以读取
ServletConfig init
参数。 - 如果是 Web 应用,可以读取
ServletContext init
参数。 - JNDI 属性来自
java:comp/env
。 - Java 系统属性(
System.getProperties()
)。 - 操作系统环境变量。
- 配置文件:application.properties、application.yml、application-{profile}.properties、application-{profile}.yml。
@PropertySource
注解导入的配置:@PropertySource(value = {"person.properties"})
。- 程序入口通过
SpringApplication.setDefaultProperties
方法设定的参数配置。@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SpringbootDemoApplication.class);
Properties properties = new Properties();
properties.setProperty("name", "learn");
springApplication.setDefaultProperties(properties);
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
6. 环境化配置 - profile
- profile 是什么机制?
- Spring 配置文件提供的一种隔离应用程序配置的方法,使其仅在特定环境中使用。
- 可通过 profile 指定 Bean 的应用环境(如开发、测试、生产环境等)。
- 可通过 profile 指定不同环境的配置参数值。
- 如何指定 profile?
- 通过配置参数
spring.profiles.active
来指定应用启动的 profiles,默认 default。 - 在环境变量中指定:jvm 参数、命令行程序参数、application.properties 中都可以。
- 代码中指定:
springApplication.setAdditionalProfiles("dev,test");
- 通过配置参数
- 如何在开发中使用?
配置文件可以存放在哪些位置?
- 当前项目运行的盘符 /config 文件夹下面:
file:./config/
。 - 当前项目运行的目录下面(命令执行的所在目录):
file:./
。 - classpath 下面的 config 文件夹:
classpath:/config
。 - classpath 的根目录(平常使用的就是这种):
classpath:/
。上述配置文件按优先级排列,排在上面的位置会覆盖优先级较低的配置。
- 当前项目运行的盘符 /config 文件夹下面:
自定义配置名称和存储路径
- SpringBoot 支持两种配置文件的格式:
.properties
、.yml
。 - yaml 语法精简版说明:
- 方式一:通过
@Value("${my.name}")
注解,将指定的参数配置注入到属性。 - 方式二:注入
Environment
对象。 ```java // 伪代码 - 注入 env 对象 @Autowired Environment environment;
// 使用示例 environment.getProperty(“name”); ```
- 方式三:通过注解
@ConfigurationProperties(prefix="my")
。- 将注解加到指定的类上,spring 会为实例对象的属性进行赋值,属性需有 getters 和 setters 方法。