Skip to content
欢迎扫码关注公众号

Spring Boot 根据配置暴露接口

SpringBoot 在 org.springframework.boot.autoconfigure.condition 包下提供了很多 ConditionalOnXxx 格式的条件注解,如 ConditionalOnBeanConditionalOnMissingBeanConditionalOnClassConditionalOnMissingClass 等。这些类名起的非常好,很直观的可以理解其功能,具体使用哪些可以根据业务需要来选择。

本示例要实现的效果:在非生产环境下暴露测试用的接口。

使用到的注解:@ConditionalOnExpressionConditionalOnBean

首先定义一个 TestEnvironment 的类:

java
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnExpression("'${my-app.env}' != 'PROD'")
public class TestEnvironment {
}

上面 @ConditionalOnExpression 注解参数中的 ${my-app.env} 为 SpEL 表达式,其值从配置文件读取。'${my-app.env}' != 'PROD' 表示如果 my-app.env 配置项的值不为 PROD,则该类生效。

因为多个地方可能会用到这个判断表达式,所以将其定义为单独的类,以方便使用和维护。

之后在测试用的 ControllerService 上加上 @ConditionalOnBean(TestEnvironment.class) 注解即可。

java
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试
 *
 * @author JiaJia
 */
@Validated
@RequiredArgsConstructor
@RestController
@ConditionalOnBean(TestEnvironment.class)
@RequestMapping("test")
public class TestController extends BaseController {

    private final TestService testService;

    /**
     * 支付测试接口
     */
    @PostMapping("/pay")
    public R<Void> pay(@Validated @RequestBody PayParam param) {
        return testService.pay(param);
    }
}

对应的测试用 Service 也是相同的写法:

java
@Service
@RequiredArgsConstructor
@ConditionalOnBean(TestEnvironment.class)
public class TestServiceImpl implements TestService {
    // ...
}

以上。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.