知识零食是一类关于零碎知识的笔记,大部分来自于对AI回答和网络搜索的整理,仅供参考

Spring项目如何通过使用配置文件中的占位符(如 ${url})来动态读取外部配置

pom文件配置,仅导入了spring-context和lombok依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.23</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

    </dependencies>

1. 配置文件中定义键值对

在 Spring 项目的application.properties或application.yml文件中定义配置信息,例如:

使用application.properties文件:

database.url=localhost:8888
database.username=root
database.password=root
database.driverName=Driver

使用application.yml文件:

database:
  url: localhost:8888
  username: root
  password: root
  driverName: Driver

2. 配置PropertySourcesPlaceholderConfigurer

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;


@Configuration
@PropertySource("classpath:application.properties") 
public class AppConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

@PropertySource注解不支持yml文件,由于纯sping项目使用yml文件过程更复杂就不介绍了

3. 使用@Value注解读取配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
public class DataConfig {

    @Value("${database.url}") // 读取配置文件中的 database.url
    private String url;

    @Value("${database.username}") // 读取配置文件中的 database.username
    private String username;

    @Value("${database.password}") // 读取配置文件中的 database.password
    private String password;

    @Value("${database.driverName}") // 读取配置文件中的 database.driverName
    private String driverName;
}
  • ${} 是占位符语法,用于引用配置文件中的键值。
  • Spring 会自动将配置文件中的值注入到对应的字段中。

4. 测试配置是否生效

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        DataConfig dataConfig = context.getBean(DataConfig.class);

        System.out.println("URL: " + dataConfig.getUrl());
        System.out.println("Username: " + dataConfig.getUsername());
        System.out.println("Password: " + dataConfig.getPassword());
        System.out.println("Driver Name: " + dataConfig.getDriverName());
    }
}

运行结果:

URL: localhost:8888
Username: root
Password: root
Driver Name: Driver

By Liu

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注