Spring的@PropertySource注解

本文介绍如何使用Spring Boot的@PropertySource注解从properties文件读取配置,并将其映射到自定义Java类中。通过示例展示了如何在People类中读取jdbc.properties配置文件中的属性,包括用户名、密码、年龄和性别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过@PropertySource注解将properties文件中的值存储到Environment中,Environment接口提供提供方法去读取配置文件中的值,参数是properties文件中配置的key值。

  1. 定义一个People类读取jdbc.properties配置文件中的值
package com.config.server.endpoint;


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



@PropertySource(value = {"classpath:jdbc.properties"})
@Component
@ConfigurationProperties(prefix = "com.yaomy.demo")
public class People {
    private String username;
    private String password;
    private int age;
    private int sex;

    //省略setter和getter方法
}
  1. properties配置文件
com.yaomy.demo.username=玛丽66
com.yaomy.demo.password=12345666
com.yaomy.demo.age=1266
com.yaomy.demo.sex=166
  1. 测试主类
package com.config.server;

import com.config.server.endpoint.People;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ApplicationContext;

@EnableConfigServer
@SpringBootApplication
public class ServerApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ServerApplication.class, args);
        People obj = context.getBean("people", People.class);
        System.out.println(obj.getUsername());
        People obj1 = context.getBean("people", People.class);
        System.out.println(obj1.getSex());


    }
}
  1. 输出的结果是
玛丽66
166
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值