????Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似于在jsp的EL表达式语言。
????Spring 开发中经常涉及调用各种资源的情况,包含普通文件、网址、配置文件、系统环境变量等,我们可以使用Spring的表达式语言实现资源的注入。
????Spring主要在注解@Value的参数中使用表达式语言。
book.author=xxx
book.name= spring boot
@Service
public class DemoService {
@Value("其他类中的属性") // 此处为注入普通字符串
private String another;
public String getAnother(){
return another;
}
public void setAnother(String anther){
this.another = anther;
}
}
@Configuration
@ComponentScan("xxx.xx.xx")
@PropertySource("classpath:test.properties")
public class ELConfig {
@Value("I Love You !") // 1
private String normal;
@Value("#{systemProperties['os.name']}") // 2
private String osName;
@Value("#{T(java.lang.Math).random() * 100.0}") // 3
private double randomNumber;
@Value("#{demoService.another}") // 4
private String fromAnother;
@Value("classpath:test.txt") // 5
private Resource testFile;
@Value("http://www.baidu.com") // 6
private Resource testUrl;
@Value("${book.name}")
private String bookName;
@Bean // 7
public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
return new PropertySourcesPlaceholderConfigurer();
}
...
setter and getter function
...
}
###### 代码解释
1. 注入普通字符串
2. 注入操作系统属性
3. 注入表达式结果
4. 注入其他Bean属性
5. 注入文件资源,文件资源可以是classpath路径下的也可以是系统文件目录下的
6. 注入网址资源
7. 注入配置文件中的资源,配置文件使用@PropertySource注解在类上标注
注入配置件需要使用@PropertySource指定文件地址,若使用@Value注入,则要配置一个PropertySourcesPlaceholderConfigurer的Bean,@Value("${book.name}")使用的是"$"而不是"#"
????Profile为不同环境下使用不同的配置提供了支持(开发环境和生成环境)
<-- Servlet 2.5及以下 -->
<serlvet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>prod</param-value>
</init-param>
</servlet>
// servlet 3.0 以上
public class WebInit implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
container.setInitParameter("spring.profiles.default", "dev");
}
}
public class DemoBean {
private String content;
public DemoBean(String content){
this.content = content;
}
public String getContent(){
return content;
}
}
@Configuration
public class ProfileConfig {
@Bean
@Profile("dev") // 1
public DemoBean devDemoBean(){
return new DemoBean("from development profile");
}
@Bean
@Profile("prod") // 2
public DemoBean prodDemoBean() {
return new DemoBean("from production profile");
}
}
###### 代码解释
1. profile为dev时示例化devDemoBean
2. profile为prod时实例化为prodDemoBean
public class Main{
public static void main(String[] args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod"); // 1
context.register(ProfileConfig.class); // 2
context.refresh(); // 3
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContext());
context.close();
}
}
###### 说明
1. 先将活动的Profile设置为prod
2. 后置注册Bean配置类,不然会报Bean未定义的错误
3. 刷新容器
原文:https://www.cnblogs.com/maosonglin/p/10641509.html