通过配置文件控制调试模式

1、方便起见直接放到config.properties

# config.properties
debugMode=true

2、DebugConfig (配置类)

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config.properties")
public class DebugConfig {

    @Value("${debugMode:false}")
    private boolean debugMode;

    // 获取调试模式的配置,默认为 false
    public boolean isDebugMode() {
        return debugMode;
    }
}

3、DebugServiceImpl (服务类)

import com.lfsun.demolfsunstudydebugbyproperties.config.DebugConfig;
import com.lfsun.demolfsunstudydebugbyproperties.service.DebugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.logging.Logger;

@Service
public class DebugServiceImpl implements DebugService {

    private static final Logger logger = Logger.getLogger(DebugServiceImpl.class.getName());

    @Autowired
    private DebugConfig debugConfig;
    @Override
    // 一个示例方法,根据调试模式输出信息
    public void process() {
        if (debugConfig.isDebugMode()) {
            logger.info("调试模式已启用,输出调试信息...");
        } else {
            logger.info("调试模式未启用,执行正常业务逻辑...");
        }

        // 其他业务逻辑
    }
}

4、DebugController (控制器类)

import com.lfsun.demolfsunstudydebugbyproperties.service.DebugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/debug")
public class DebugController {

    private final DebugService debugService;

    @Autowired
    public DebugController(DebugService debugService) {
        this.debugService = debugService;
    }

    @GetMapping("/process")
    public String processDebug() {
        debugService.process();
        return "Debug 处理完成~";
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/134686363
今日推荐