springboot PropertySource的使用

如果需要把application.properties配置中的一些配置内容,独立出来,我们可以使用PropertySource来读取单独的配置文件,仅支持properties类型,yml需要自己手动代码再实现

贴代码

person.java

package com.shrimpking.demo1;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/12/22 11:27
 */
@Data
@Component
@PropertySource(value = "classpath:person.properties")
public class Person
{
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
    @Value(("${person.boss}"))
    private Boolean boss;
    //不支持@value
    private Map<String,Object> maps;
    //不支持@value
    private List<String> lists;
    //不支持@value
    private Dog dog;

}

dog.java

package com.shrimpking.demo1;

import lombok.Data;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/12/22 11:29
 */
@Data
public class Dog
{
    private String name;
    private Integer age;
}

application.properties

server.port=8089

person.properties

person.name=zhangsan
person.age = 18
person.boss = false
person.maps.k1 = v1
person.maps.k2 = v2
person.lists = a,b,c
person.dog.name = tom
person.dog.age = 2

controller.java

package com.shrimpking.demo1;

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

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/12/22 11:32
 */
@RestController
public class TestController
{
    @Autowired
    private Person person;

    @GetMapping("/test")
    public String test(){
        return person.toString();
    }
}

启动类

package com.shrimpking.demo1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
public class Demo1Application
{

    public static void main(String[] args)
    {
        SpringApplication.run(Demo1Application.class, args);
    }

}

注意,使用propertysource时,只能配合使用@value来获取值,并且只能获取简单类型的值,复杂类型,比如数据,map,类对象等不支持。

另外propertysource仅支持properties类型的,yml需要自己增加代码支持。

  • 14
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

虾米大王

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

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

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

打赏作者

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

抵扣说明:

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

余额充值