简体   繁体   中英

How to get property value from application.properties file on spring boot project?

Below is my code and configuration, but I can't get properties' value, always null .


application.properties

app.myProperty=1234

class AppProperties:

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

    private String myProperty;

    public String getMyProperty() {
        return myProperty;
    }

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

Controller:

@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));
        }
    }

}

log output:

property value:null

Use @Value annotation to read the values from application.properties

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM