假设要读取 application.yml下面的内容
people:
name: csj
addr: henan
方法一:单个读取用 @Value 如下:
package test;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = com.zzyl.ZzylApplication.class)
@Slf4j
public class TestBeans {
@Value("${people.name}")
private String name;
@Test
public void testSingle(){
log.info("测试name: {}",name);
}
}
效果如下:
注意:注解里的值别忘记用${}包起来,不然就会当做普通字符串注入,引用的地方可能会有空指针错误(如下)
方法二:批量注入先定义配置类,然后上面用@ConfigurationProperties+@Component 然后在使用的地方用 @Autowired注解注入如下:
配置文件TestPeopleConfig.java
package com.zzyl.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "people")
@Data
public class TestPeopleConfig {
private String name;
private String addr;
}
测试效果源代码:
@Autowired
private TestPeopleConfig testPeopleConfig;
@Test
public void testBatch(){
log.info("name: {}",testPeopleConfig.getName());
log.info("addr: {}",testPeopleConfig.getAddr());
}
效果:
说明:
@Component:把对象的创建权交给IOC容器
@ConfigurationProperties 把外部配置绑定到java对象上
@Component+@ConfigurationProperties 目前是将配置绑定的java对象可以注入到其他地方
prefix 配置属性的前缀