温馨提示×

springboot读取properties配置文件

小亿
51
2024-01-04 03:15:11
栏目: 编程语言

在Spring Boot中,可以使用@ConfigurationProperties注解来读取properties配置文件。

首先,需要在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

然后,在配置类中使用@ConfigurationProperties注解,并指定properties文件的前缀,示例如下:

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

@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
    private String name;
    private String age;

    // getter and setter methods
}

在配置文件中,使用myconfig作为前缀来定义属性,示例如下:

myconfig.name=John
myconfig.age=25

最后,可以在其他类中通过@Autowired注解来注入配置类,并使用其中的属性,示例如下:

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

@Component
public class MyService {
    @Autowired
    private MyConfig myConfig;

    public void printConfig() {
        System.out.println("Name: " + myConfig.getName());
        System.out.println("Age: " + myConfig.getAge());
    }
}

这样,配置文件中的属性值就会被自动注入到MyConfig类中,并可以在其他类中使用。

0