Spring学习之路5——Espl表达式

没啥可说的,就是动态获取值,感觉有点类似Jsp。

付个小demo。虽然之前说了不再使用xml配置,但是为了覆盖到不同的知识点还是用一下。

package com.glodon.springdemo5;

public class NumberGuess {
  public double getRandomNumber() {
    return randomNumber;
  }

  private double randomNumber;

  public void setRandomNumber(double randomNumber) {
    this.randomNumber = randomNumber;
  }

  @Override
  public String toString() {
    return "com.glodon.springdemo5.NumberGuess{" +
        "randomNumber=" + randomNumber +
        '}';
  }
}

在配置bean中动态获取值:

package com.glodon.springdemo5;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
  @Bean
  public User user(@Value("#{numberGuess.getRandomNumber()}") int age, @Value("#{numberGuess.getRandomNumber() < 20? 'young' : 'old'}") String desc) {
    User user = new User();
    user.setAge(age);
    user.setDesc(desc);
    return user;
  }
}

xml配置文件:




  
  

  

  
    
    
  

然后在测试类中就能打印出来,numberguess自己按照xml配置文件生产的数字了,而且还能执行大小逻辑判断:

package com.glodon.springdemo5;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    User user = ctx.getBean(User.class);
    System.out.println(user);
  }
}

 

你可能感兴趣的:(Spring,java)