温馨提示×

springboot怎么获取properties属性

小亿
91
2024-06-03 19:20:09
栏目: 深度学习

在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文件中的属性值了。

0