spring boot学习之配置文件属性映射

1.配置

使用application.properties或application.yml
在src/main/resources目录下,你可以创建application.properties或application.yml文件来配置你的应用

application.properties
# 服务器端口
server.port=8080

# 数据库连接
spring.datasource.url=jdbc:mysql://localhost:3306/yourdatabase
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

application.yml
server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/yourdatabase
    username: root
    password: secret
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

2.配置文件中值映射到代码中

2.1使用@Value注解

你可以在Spring Bean中直接使用@Value注解来注入配置属性。

点击查看代码

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

@Component
public class MyBean {
    @Value("${server.port}")
    private String port;
    // 其他代码...
}

2.2 使用@ConfigurationProperties注解(批量映射指定prefix下的所有值)

对于更复杂的配置,你可以使用@ConfigurationProperties注解,并将其绑定到一个Bean上。首先,确保你的类上使用@ConfigurationProperties(prefix = "some.prefix")注解,然后使用@EnableConfigurationProperties注解在你的配置类上启用它。

点击查看代码
配置文件application.yml:
app:
  name: MyApp
  version: 1.0

代码中:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private String name;
    private int version;
    // getters and setters...
}
posted @ 2025-11-24 15:43  小一爱学习  阅读(0)  评论(0)    收藏  举报