有參數文件以下test.propertiesjava
project.author=wpfc project.create_time=2018/3/29
在系統中讀取對應的數據,並注入到屬性中測試
@Configuration @ComponentScan("cn.edu.ntu") @PropertySource("classpath:test.properties") public class ElConfig { @Value("#{systemProperties['os.name']}") private String osName; //要想使用@Value 用${}佔位符注入屬性,這個bean是必須的(PropertySourcesPlaceholderConfigurer), //這個就是佔位bean, //另外一種方式是不用value直接用Envirment變量直接getProperty('key') @Value("${project.author}") public String author; @Autowired private Environment environment; //You need this if you use @PropertySource + @Value @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public void printProperties(){ System.out.println("os name : " + osName); System.out.println("author : " + author); System.out.println("env : " + environment.getProperty("project.create_time")); } }
測試方法:this
public class MainApplication { public static void main(String[] args){ AnnotationConfigApplicationContext context = null; context = new AnnotationConfigApplicationContext(ElConfig.class); ElConfig bean = context.getBean(ElConfig.class); bean.printProperties(); } }
測試結果:spa
os name : Windows 7 author : wpfc env : 2018/3/29
@Import 引入javaConfig配置的配置類 @ImportResource 引入xml對應的配置文件