博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
@PropertySource读取配置文件通过@Value进行参数注入
阅读量:7259 次
发布时间:2019-06-29

本文共 1377 字,大约阅读时间需要 4 分钟。

hot3.png

有参数文件如下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对应的配置文件

 

转载于:https://my.oschina.net/u/2326864/blog/1786955

你可能感兴趣的文章