如何从Spring Boot项目上的application.properties文件获取属性值?

时间:2019-04-19 02:03:00

标签: java spring-boot spring-mvc

下面是我的代码和配置,但我无法获取属性的值,总是空


application.properties

  

app.myProperty = 1234

AppProperty类:

@Component
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {

    private String myProperty;

    public String getMyProperty() {
        return myProperty;
    }

    public void setMyProperty(String myProperty) {
        this.myProperty = myProperty;
    }
}

控制器:

@RestController
@Slf4j
public class TestController {

    @Autowired
    AppProperties appProperties;

    @PostMapping(RoutePath.TEST)
    public ResultVO test() {

        try {

            log.info("property value:" + appProperties.getMyProperty());

            return ResultVOUtil.success(null);

       } catch (Exception ex) {

            return ResultVOUtil.error(CommonUtil.logExceptionError("发生错误。", null, ex));
        }
    }

}

日志输出:

  

属性值:空

1 个答案:

答案 0 :(得分:0)

使用@Value批注从application.properties读取值

@Value("$(myProperty)")
private String myProperty;