有参数文件如下test.properties
project.author=wpfcproject.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")); } }
测试方法:
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(); } }
测试结果:
os name : Windows 7author : wpfcenv : 2018/3/29
@Import 引入javaConfig配置的配置类@ImportResource 引入xml对应的配置文件