1.整体目录结构如下
2.pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>chengf</groupId> <artifactId>spring-property-test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-property-test</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.5.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.5.RELEASE</version> </dependency> </dependencies> </project>
3.Appconfig类
package chengf.spring.property.test; import org.springframework.beans.factory.annotation.Value; /** * @author chengf * */ public class AppConfig { @Value("${name}") private String name; @Value("${age}") private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
4.properties 文件
name=chengf age=20
5.测试类
package chengf.spring.property.test; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @ContextConfiguration public class AppConfigTest { @Configuration @PropertySource(value = { "classpath:test.properties" }) public static class Config { @Bean public AppConfig appConfig() { return new AppConfig(); } @Bean public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer () { return new PropertySourcesPlaceholderConfigurer (); } } @Autowired private AppConfig appConfig; @Test public void test() { Assert.assertEquals("chengf", appConfig.getName()); Assert.assertEquals(20, appConfig.getAge()); } }
junit 测试通过,表明已经通过@Value正确注入了properties中的属性