我正在尝试通过Automation项目中的org.springframework.core.env.Environment
加载属性。但我认为环境是无效的。以下是我的配置。
pom:中的依赖项
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
details.properties
:放置在src/main/resources 下
group=RandomCheck
varry=RandomMonth
check=RandomDay
属性配置类-TestProperty.java
@Configuration
@PropertySource("classpath:details.properties")
public class TestProperty{
@Autowired
Environment env;
@Test
public void testPro(){
System.out.println(env.getProperty("group"));
}
}
在执行这个JUnit测试之后,由于环境的原因,我得到了空指针。我是否遗漏了任何配置或做错了什么?
我试着在上下文的应用程序上下文帮助下阅读:属性占位符和@Value。值也返回null。有人能帮忙吗?谢谢
混合src
和test
环境。不要使用@Test
,而是尝试使用@PostConstruct
。
@Configuration
@PropertySource("classpath:details.properties")
public class TestProperty{
@Autowired
Environment env;
@PostConstruct
public void testPro(){
System.out.println(env.getProperty("group"));
}
}
对于此类的单元测试:
@SpringBootTest
@TestPropertySource("classpath:details.properties")
public class TestPropertyTest {
@Autowired
Environment env;
@Test
void unitTest() {
// test stuff
}
}