天天看點

深入淺出springboot2.x(5)

使用spring EL

SpringEL表達式代碼案例一:

@Component
public class SpringELDemo1 {
    //調用方法
    @Value("#{T(System).currentTimeMillis()}")
    private long initTime;
    //給字元串指派
    @Value("#{'使用spring EL指派字元串'}")
    private String str;
    //指派浮點數
    @Value("#{3.14}")
    private float aFloat;
    //數學運算
    @Value("#{1+2}")
    private int number;
    //字元串拼接
    @Value("#{springELDemo1.str+'拼接字元串'}")
    private String strAdd;
    //三目運算
    @Value("#{springELDemo1.number>5 ? '大于':'小于'}")
    private String result;
    。。。getter and setter。。。
}
           

@Value("#{…}")用來擷取bean屬性或者調用方法,也能進行一些運算功能。

@Value("#{springELDemo.str+‘拼接字元串’}")中springELDemo是IOC容器bean的名稱,str是屬性。

測試代碼:

@ComponentScan
public class SpringELConfig {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ScopeTestConfig.class);
        SpringELDemo1 springELDemo = ctx.getBean(SpringELDemo1.class);
        System.out.println("調用方法結果::"+springELDemo.getInitTime());
        System.out.println("給字元串指派::"+springELDemo.getStr());
        System.out.println("指派浮點數::"+springELDemo.getaFloat());
        System.out.println("數學運算::"+springELDemo.getNumber());
        System.out.println("字元串拼接::"+springELDemo.getStrAdd());
        System.out.println("三目運算::"+springELDemo.getResult());
    }
}
           

輸出結果:

調用方法結果::1562060184454
給字元串指派::使用spring EL指派字元串
指派浮點數::3.14
數學運算::3
字元串拼接::使用spring EL指派字元串拼接字元串
三目運算::小于
           

SpringEL表達式代碼案例二:

在application.properties配置檔案中配置一個字元串

spring.el.name = elName
           
@Value("${el.name}")
    String elName;
           

用@Value("

$

{。。。}")取值。${…}代表占位符,它會讀取上下文的屬性值裝配到屬性中。

繼續閱讀