springboot配置文件(二)

本文详细介绍SpringBoot中如何通过简单引用和扩展引用的方式读取配置文件内容,并演示了具体的实现步骤,包括创建配置文件、编写控制器代码以及实体类。

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

springboot读取配置方法:

一、简单引用

1、在app.properties文件中编写内容,

com.redxun.name = 测试
com.redxun.want = spring boot
com.redxun.sum = ${com.redxun.name} +${com.redxun.want}

2、在controller中使用:

@RestController
@EnableConfigurationProperties({ConfigBean.class})
public class UserController {
    @Autowired
    ConfigBean configBean;
    
    @RequestMapping("/")
    public String index(){
        return "Hello spring boot!" + configBean.getSum();
    }
}

3、配置文件实体类:

@Component
@ConfigurationProperties(prefix = "com.redxun")
public class ConfigBean {
    private String name;
    private String want;
    private String sum;

    /*
        get/set   
    */
}

4、app.properties内容在页面显示乱码问题:

如图,勾上Transparent native-to-ascii conversion即可。

5、最终效果:

二、扩展引用:

1、引用自定义的properties文件:

新建一个test.properties文件,引入方式跟缺省配置文件几乎一样,区别在于在此需要制定引用路径:

@Configuration
@ConfigurationProperties(prefix = "com.md")
@PropertySource("classpath:test.properties")   // 指定引用路径

参考资料:springboot干货

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值