@Value(“${}”)注解
该注解来自spring-beans.jar.使用频率较高,但一次只能接收一个字段
Environment对象中获取
该类源于spring-core.jar.使用频率较低 ,缺点也是一次只接收一个字段值
@ConfigurationProperties(“”)注解
该注解来自spring-boot.jar.一次可以接收多个字段的值,将多字段映射成一个javaBean.适用于多字段同时管理
测试用例(spring-boot)
1.pom.xml,只贴用到的依赖
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.4.11</version>
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.application.yml
spring:
application:
name: java8-demo
thread:
pool:
core-pool-size: 10
person:
name: zhangsan
age: 18
gender: -1
address: XXX看守所
3.测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class AppTest {
@Autowired
private Environment environment;//spring-core
@Value("${spring.application.name}")
private String applicationName;
@Value("${spring.application.name}")//spring-beans
private static String name;
@Resource
private PersonIOC personIOC;
@Test
public void testPropertiesIOC() {
System.out.println("core-pool-size:" + environment.getProperty("thread.pool.core-pool-size"));
System.out.println("core-pool-size:" + environment.getProperty("thread.pool.corePoolSize"));//格式不对接收不到
System.out.println("=====");
System.out.println("applicationName:" + applicationName);
System.out.println("applicationName:" + name);//使用static修饰接收不到
System.out.println("====");
System.out.println(personIOC);
}
}
4.运行结果
core-pool-size:10
core-pool-size:null
=====
applicationName:java8-demo
applicationName:null
====
PersonIOC(name=zhangsan, age=18, gender=-1, address=XXX看守所)