springboot怎么获取properties属性

1949idc 2年前 (2024-09-18) 阅读数 334 #深度学习

在Spring Boot中,可以通过@Autowired注解将properties属性注入到一个bean中,然后通过该bean来获取属性值。

首先,创建一个Java类用来存储properties属性值,例如:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
    private String property1;
    private int property2;

    // getter and setter methods
}

在application.properties文件中定义属性值:

myapp.property1=value1
myapp.property2=123

然后,在需要获取属性值的地方,使用@Autowired注解注入MyAppProperties类,然后就可以通过该类的getter方法获取属性值:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Autowired
    private MyAppProperties myAppProperties;

    public void someMethod() {
        String property1 = myAppProperties.getProperty1();
        int property2 = myAppProperties.getProperty2();

        // 使用属性值
    }
}

这样就可以获取到定义在application.properties文件中的属性值了。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业