SpringBoot Profile的设置
1、我们捂执涡扔使用Spring Boot框架进行开发,使用Maven进行jar包和配置的管理,因此我们此处不再介绍。我们在pom文件中配置<profiles>,添加两个<profile媪青怍牙>,其中默认的为dev本地开发环境,<activeByDefault>为true。prod为现网环境,我们在正在部署的时候可以修改这个设置,通过使用mvn命令打包时指定即可。<profiles> <profile> <id>dev</id> <properties> <profileActive>dev</profileActive> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>prod</id> <properties> <profileActive>prod</profileActive> </properties> </profile></profiles>
2、我们在配置文件application.properties中使用spring.profiles.active的配置指定配置文件的使用,其值为spring.profiles.act足毂忍珩ive=@profileActive@表示使用指定的配置,该配置若为dev,则会从application-dev.properties这个配置中读取属性,若为prod,则会从application-prod.properties中读取该属性。
3、我们在开发中还可以使用@Profile注解在类或方法上,来达到在不同的环境下实例化不同的bean或者使用不同的方法的目的。我们创建一个DemoBean类,给定一个属性content,并创建一个构造方法用于实例化bean。
4、接下来我们创建一个配置类,@Configuration表明该类是一个配置类,@Bean注解表明会实例化该bean,@Profile注解制定实例化该bean的环境,如下图所示。
5、最后我们编写测试类,在测试类中我们通过设置Environment的ActiveProfiles来设定当前context需要使用的环境变量。context.getEnvironment().setActiveProfiles("prod");指定当前环境为生产环境,然后注册该配置类并更新context,代码如下图所示。
6、根据运行结果可以看出实例化的是生产环境的bean,可以修改context.getEnvironment().setActiveProfiles("dev"),然后再执行测试方法,此时实例化的为测试环境的bean。