springboot @value类型安全的配置(基于properties)

上例中使用@Value注入每个配置在实际项目中会显得格外麻烦,因为我们的配置通常会是许多个,若使用上例的方式则要使用@Value注入很多次。

Spring Boot还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全的配置。

添加配置,即在application.properties上添加:

author.name = shrimp king
author.age = 99

当然,我们也可以新建一个properties文件,这就需要我们在@ConfigurationProperties的属性locations里指定properties的位置,且需要在类上配置。

我这里建立了mytest.properties

server.port=8089
server.context-path=/t1
author.name = shrimp king
author.age = 99

类型安全的Bean,代码如下:

package com.shrimpking.Test2;

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

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/1/7 17:33
 */
@Component
@ConfigurationProperties(prefix = "author",locations = {"classpath:mytest.properties"})
public class AuthorSettings
{
    private String name;

    private Long age;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Long getAge()
    {
        return age;
    }

    public void setAge(Long age)
    {
        this.age = age;
    }
}

通过@ConfigurationProperties加载properties文件内的配置,通过prefix属性指定properties的配置的前缀,通过locations指定properties文件的位置,例如:@ConfigurationProperties(prefix = "author",locations = {"classpath:mytest.properties"}) 

package com.shrimpking.Test2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/1/7 17:31
 */
@RestController
public class Test2Controller
{
    @Autowired
    private AuthorSettings authorSettings;

    @RequestMapping(value = "/index2",method = RequestMethod.GET)
    public String index2(){
        return "author name is: " + authorSettings.getName()
                + " and author age is: " + authorSettings.getAge();
    }
}

可以用@Autowired直接注入该配置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值