笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

关于Spring Profiles的使用

Posted on 2024-03-30 16:41  草妖  阅读(8)  评论(0)    收藏  举报

当时看到Spring Profiles时,最开始的想法是这个东西是否是可以在同一个spring boot的程序中配置多个不同IP的数据库,进行了解的,最后才发现Spring Profiles的作用是在解决不同生产环境下数据库连接等不同配置进行指定激活处理。

注:目前个人使用发现较为鸡肋,本人针对不同的环境配置信息的不同,往往是直接保存成特定文件发布时直接黏贴处理(相对而言,即不会存在无效/不使用的文件占安装包大小,也不需要过多配置不同环境开启使用的Bean)。如需了解请查阅相加详细的博客,本文仅作使用笔记记录

一、配置不同的profile

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("V0")
public class PublicV0ServiceImpl {
    public void V0(){
        System.out.println("V0...");
    }
}


@Component
@Profile("V1")
public class PublicV1ServiceImpl {
    public void V1(){
        System.out.println("V1...");
    }
}

 

 

二、进行Profile的使用

 

import com.namejr.serviceImpl.PublicV0ServiceImpl;
import com.namejr.serviceImpl.PublicV1ServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/Public")
@Tag(name = "PublicController", description = "控制器")
public class PublicController {
    @Autowired(required = false)  // 注:一定要补充“required = false”,因为自动状态Bean默认是required=true,且往往只能激活一种profile,所以不指定的情况下会报后面补充的错误。
private PublicV0ServiceImpl p0erviceImpl;
@Autowired(required = false)
private PublicV1ServiceImpl p1erviceImpl;

    @RequestMapping(value = "/V0", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @Operation(summary = "V0")
    public void getResGuid() {
        System.out.println("===========V0========Start=======");
        p0erviceImpl.V0();
        System.out.println("===========V0========End=======");
    }

    @RequestMapping(value = "/V1", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @Operation(summary = "V1")
    public void V1() {
        System.out.println("===========V1========Start=======");
        p1erviceImpl.V1();
        System.out.println("===========V1========End=======");
    }
}

 

 

三、执行开启活动状态的profile

 

application.properties文件配置
    spring.profiles.active=V0

 

 

不指定Autowired报的错误