具体做法:
1、首先在pom中添加profiles:
dev truedev org.springframework.boot spring-boot-devtoolstrue org.springframework.boot spring-boot-starter-undertowprod org.springframework.boot spring-boot-starter-undertowprod
dev指开发模式,prod指生产模式,如需其他模式,只需要添加profile即可.
2、在pom.xml的build中添加plugin:
org.apache.maven.plugins maven-resources-plugin${maven-resources-plugin.version} default-resources validate copy-resources target/classes false # src/main/resources/ true ***.yml src/main/resources/ false ***.yml
该配置用来在打包的时候修改配置文件。
3、编写DefaultProfileUtil工具类来添加默认启动配置文件:
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.Environment;
import java.util.HashMap;
import java.util.Map;
public final class DefaultProfileUtil {
private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
private DefaultProfileUtil(){
}
public static void addDefaultProfile(SpringApplication app) {
Map defProperties = new HashMap<>();
defProperties.put(SPRING_PROFILE_DEFAULT, Constants.SPRING_PROFILE_DEVELOPMENT);
app.setDefaultProperties(defProperties);
System.out.println(app);
}
public static String[] getActiveProfiles(Environment env) {
String[] profiles = env.getActiveProfiles();
if (profiles.length == 0) {
return env.getDefaultProfiles();
}
return profiles;
}
}
public class Constants {
public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
public static final String SPRING_PROFILE_PRODUCTION = "prod";
private Constants() {
}
}
4、修改application.yml配置文件,添加(采用application.properties文件):
spring: profiles: active: #spring.profiles.active#
maven的构建的时候会替换#spring.profiles.active#
5、修改项目的启动类:
@SpringBootApplication
public class Demo1Application {
private static final Logger log = LoggerFactory.getLogger(Demo1Application.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Demo1Application.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
log.info("n----------------------------------------------------------nt" +
"Application '{}' is running! Access URLs:nt" +
"Local: tthttp://localhost:{}nt" +
"----------------------------------------------------------",
env.getProperty("spring.application.name"),
env.getProperty("server.port"));
}
}
以上修改完成之后,在启动的时候会显示:The following profiles are active: dev 默认dev模式切换成功。
6、构建项目:
采用mvn clean package -Pprod命令构建,最后的配置文件会被改成:
以上就是spring boot实现profiles动态切换的示例的详细内容,更多关于spring boot实现profiles动态切换的资料请关注考高分网其它相关文章!



