1、使用@Value注解
- 1.1 @Value的基本使用
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@Value("${myapp.name}")
private String appName;
public void printAppName() {
System.out.println(appName);
}
}
- 1.2 @Value的高阶使用
/**************************************************************************
${…} 主要用于加载配置文件中的配置项值,可设置默认值;
#{…} 主要用于通过spring的EL表达式,获取bean的属性、调用bean的方法、调用类的静态常量和静态方法,并将内容赋值给属性;
${…} 和 #{…} 可以混合使用,#{}在外面,${}在里面;
**************************************************************************/
@Value("${string:}") //默认空字符串
private String string;
@Value("#{'${code1:,}'.split(',')}") //默认空list
private List<String> codeList;
@Value("#{'${code1:1,2}'.split(',')}") //默认[1,2]
private List<String> codeList;
@Value("#{'${code2:,}'.split(',')}") //默认空set
private Set<String