- 读取的配置文件
application.yml
:
jianshu:
id: futaosmile
# 1. 使用@ConfigurationProperties注解注入
@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties(prefix = "jianshu")
public class SpringmvcdemoApplicationTests {
private String id;
@Test
public void test10() {
System.out.println(id);
}
}
- 输出
null
,注入失败 - 原因:使用
@ConfigurationProperties
注解的方式注入为每个注入的字段添加setter方法
package com.futao.springmvcdemo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties(prefix = "jianshu")
public class SpringmvcdemoApplicationTests {
private String id;
@Test
public void test10() {
System.out.println(id);
}
public void setId(String id) {
this.id = id;
}
}
-
输出:
@ConfigurationProperties注入
# 2. 使用@Value注解
package com.futao.springmvcdemo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringmvcdemoApplicationTests {
@Value("${jianshu.id}")
private String id;
@Test
public void test10() {
System.out.println(id);
}
}
-
输出:
@Value注解
OK
网友评论