为什么要使用多环境配置
在实际开发中,应用程序通常需要部署到不同的运行环境中,例如开发环境、测试环境、生产环境等。不同的环境可能需要不同的环境配置,针对这种情况,不可能手动变更配置文件来适应不同的开发环境,通常需要对项目进行多环境配置,Spring Boot框架提供了两种多环境配置的方式,分别是Profile文件多环境配置和@Profile注解多环境配置。
使用Profile文件进行多环境配置
一、创建项目ProfileDemo01
二、创建多环境配置文件
- 将application.properties文件后缀改为yaml
- 配置文件命名格式:application-xxx.yaml,如果不是application则会被认定为自定义配置文件
三、创建控制器ProfileController
- 创建controller子包
package net.lj.lesson05.profiledemo01.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 项目资料控制器
*/
@RestController
public class ProfileController {
@GetMapping("hello")
public String hello(){
return "Hello Spring Boot";
}
}
使用全局配置文件指定使用环境
启动项目进行测试
- 可以清楚看到配置的环境信息
修改环境再次查看
通过命令行方式
- 使用IDEA将Maven项目打成jar包
- 在target目录会生成的项目jar包
- 在终端执行jar包,选择使用环境 - 开发环境
cd target
java -jar profiledemo01-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
- 可以看到,使用环境不受全局配置文件的影响
Ctrl+C停止运行
使用@Profile注解进行多环境配置
- @Profile注解适用于项目将用到多种数据库的环境
一、创建项目ProfileDemo02
二、创建数据库配置接口DatabaseConfig
- 创建config子包
package net.lj.lesson05.config;
/**
* 数据库配置接口
*/
public interface DatabaseConfig {
void connector();
}
三、创建数据库配置实现类MySQLConfig
package net.lj.lesson05.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* MySQL数据库配置类
*/
@Configuration // 指定为配置类
@Profile("mysql") // 指定配置环境名称
public class MySQLConfig implements DatabaseConfig {
@Override
public void connector() {
System.out.println("项目使用MySQL数据库环境~");
}
}
四、创建数据库配置实现类OracleConfig
package net.lj.lesson05.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* Oracle数据库配置类
*/
@Configuration // 指定为配置类
@Profile("oracle") // 指定配置环境名称
public class OracleConfig implements DatabaseConfig {
@Override
public void connector() {
System.out.println("项目使用Oracle数据库环境~");
}
}
五、创建数据库配置实现类SybaseConfig
package net.lj.lesson05.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* Sybase数据库配置类
*/
@Configuration // 指定为配置类
@Profile("sybase") // 指定配置环境名称
public class SybaseConfig implements DatabaseConfig {
@Override
public void connector() {
System.out.println("项目使用Sybase数据库环境~");
}
}
六、在全局配置文件application.properties里配置使用环境
七、编写测试方法
package net.lj.lesson05;
import net.lj.lesson05.config.DatabaseConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProfileDemo02ApplicationTests {
@Autowired
private DatabaseConfig databaseConfig;
@Test
void contextLoads() {
//调用数据库配置实体方法
databaseConfig.connector();
}
}