SpringBoot:高级特性

Profile环境切换

配置文件可以写多个通过application-xxx.yaml来区别不同的生产环境。
比如
在这里插入图片描述
这里创建了三个配置文件,不加后缀的是默认配置环境,项目启动时默认配置文件加载,根据spring.profile.active来选择不同的配置文件激活,默认配置和指定环境的配置文件都生效,如果有同名的配置则指定生产环境生效。
application.yaml

spring:
  profiles:
   	active: dev
   	# dev环境激活

application-dev.yaml

person:
  name: "dev"

application-test.yaml

person:
  name: "test"

这里写一个controlller来测试一下

@Controller
public class ProfileController {
    @Value("${person.name}")
    String name;
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello"+name;
    }
}

激活不同的测试环境或者不激活使用默认配置。
这里也可以换一种玩法,创建一个类,使用配置文件绑定对应信息然后返回。
准备一个Person类,注意要加getter和setter否则没法绑定

@Data
@Component
@ConfigurationProperties("person")
public class Person {
    String name;
    Integer age;
}

application.yaml

person:
  name: "默认环境"
  age: 20

application-dev.yaml

person:
  name: "dev"
  age: 18

application-test.yaml

person:
  name: "test"
  age: 19

Controller

@Controller
public class ProfileController {
    @Autowired
    Person person;
    @RequestMapping("/hello")
    @ResponseBody
    public Person hello(){
        return person;
    }
}

Profile条件装配

现在我们想实现根据不同的生产环境接口的实现类也发生改变。
先创建一个接口和两个实现类
在这里插入图片描述
通过@Profile注解来实现在不同生产环境下装配不同的类,举个例子我们现在需要在dev环境下装配Boss,test环境下装配Worker。这两个类同时继承了Company接口。
Company

public interface Company {
}

Worker

import com.example.boot2admin.profile.Company;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Data
@Component
@Profile("test")
@ConfigurationProperties("person")
public class Worker implements Company {
   private String name;
   private Integer age;
}

Boss

import com.example.boot2admin.profile.Company;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Data
@Component
@Profile("dev")
@ConfigurationProperties("person")
public class Boss implements Company {
   private String name;
   private Integer age;


}

配置文件不变,就可以实现不同生产环境的条件装配了。

Profile分组

比如说我们想合并两个配置文件,这个时候我们可以使用分组的方式实现。
application.yaml:这里是将dev和prod两个环境合并成一个环境起名叫product并激活这个环境

spring:
  profiles:
    active: product
    group:
      product[0]: dev
      product[1]: prod
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值