一:说明
Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似于JSP的EL表达式语言。
Spring 开发中经常涉及调用各种资源的情况,包含普通文件,网址,配置文件,系统环境变量等。 我们可以使用Spring的表达式语言实现资源的注入。
二:代码实例
-
@Service
-
public class DemoService {
-
@Value("其他类的属性")
-
private String another;
-
-
/**
-
* @return the another
-
*/
-
public String getAnother() {
-
return another;
-
}
-
-
/**
-
* @param another
-
* the another to set
-
*/
-
public void setAnother(String another) {
-
this.another = another;
-
}
-
-
}
-
@Configuration
-
@ComponentScan("com.gemdale")
-
@PropertySource("classpath:com/gemdale/gmap/spring/boot/demo/el/test.properties")
-
public class ElConfig {
-
@Value("I love youe!")
-
private String normal;
-
-
@Value("#{systemProperties['os.name']}")
-
private String osName;
-
-
@Value("#{ T(java.lang.Math).random() * 100.0 }")
-
private double randomNumber;
-
-
@Value("#{demoService.another}")
-
private String fromAnother;
-
-
@Value("classpath:com/gemdale/gmap/spring/boot/demo/el/test.txt")
-
private Resource testFile;
-
-
@Value("http://www.baidu.com")
-
private Resource testUrl;
-
-
@Value("${book.name}")
-
private String bookName;
-
-
@Autowired
-
private Environment environment;
-
-
@Bean
-
public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
-
return new PropertySourcesPlaceholderConfigurer();
-
}
-
-
public void outputResource() {
-
try {
-
System.out.println(normal);
-
System.out.println(osName);
-
System.out.println(randomNumber);
-
System.out.println(fromAnother);
-
System.out.println(IOUtils.toString(testFile.getInputStream()));
-
System.out.println(IOUtils.toString(testUrl.getInputStream()));
-
System.out.println(bookName);
-
System.out.println(environment.getProperty("book.author"));
-
}
-
catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
public class Start {
-
public static void main(String[] args) throws Exception {
-
-
AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(
-
ElConfig.class);
-
ElConfig resourceService = configApplicationContext.getBean(ElConfig.class);
-
resourceService.outputResource();
-
-
configApplicationContext.close();
-
}
-
}
-
book.author=GH
-
book.name=spring boot
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28624388/viewspace-2133687/
,如需转载,请注明出处,否则将追究法律责任。