springboot配置文件加载

springboot配置文件加载

这里是springboot加载相应文件汇总内容,内容持续更新。

  1. yml文件加载
  2. 读取普通的properties文件
  3. 读取bean配置文件
  4. 待续…

一、yml文件加载

1 yml文件案例

server:
  servlet:
    context-path: /spring-web
  port: 8081
person:
  username: 张三
  age: 18
  birth-date: 2020/8/3
  hobby: ["篮球","听歌","写作"]
  others:
    key1: value1
    key2: value2
  work-contents:
    - key1: key11
    - key2: key22

加载方式: 使用@ConfigurationProperties注解

@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String username;
    private Integer age;
    private Date birthDate;

    private List<String> hobby;
    private Map<String,Object> others;

    private List<Map<String,Object>> workContents;
    ... setter 
    ... getter
 }
# 测试案代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringMain.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringMainTest {
    @Autowired
    protected Person person;

    @Test
    public void test01() {
        System.out.println(person);
        //System.out.println(userService);
        //System.out.println(helloService01);
    }
}

效果如下:

Person{username='张三', age=18, birthDate=Mon Aug 03 00:00:00 CST 2020, hobby=[篮球, 听歌, 写作], others={key1=value1, key2=value2}, workContents=[{key1=key11}, {key2=key22}]}

二、加载普通的properties

person.username=李四
person.age=20
person.birthDate=2020/8/4

加载方式: 使用@PropertySource注解+@Value注解

@PropertySource(value = {"classpath:person.properties"},encoding = "UTF-8")
public class Person {

    @Value("${person.username}")
    private String username;
    @Value("${person.age}")
    private Integer age;
    @Value("${person.birthDate}")
    private Date birthDate;

### 注意设置编码###

效果如下:

Person{username=‘李四’, age=20, birthDate=Tue Aug 04 00:00:00 CST 2020, hobby=null, others=null, workContents=null}

三、加载bean配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     <bean id="userService" class="com.walker.web.service.UserService"></bean>
</beans>

加载方式 :@ImportResource(locations = {“classpath:bean.xml”})

@ImportResource(locations = {"classpath:bean.xml"})
public class SpringMain {

    public static void main(String[] args) {
        SpringApplication.run(SpringMain.class,args);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值