BeanExpressionContext實現@Value的功能

@SpringBootApplication
public class CommissionServiceAppliction {

    public static void main(String[] args) {
        ConfigurableApplicationContext app = new SpringApplicationBuilder(CommissionServiceAppliction.class).run(args);
        ConfigurableEnvironment environment = app.getEnvironment();
        System.out.println(environment.getProperty("spring.application.name") + "服務啓動完畢...");
        System.out.println("--------------------測試@Value開始---------------------");
        //計算一個具體的值(非表達式)
        System.out.println(resolveExpression(app.getBeanFactory(), "1121"));
        //實現@Value的功能
        System.out.println(resolveExpression(app.getBeanFactory(), "${kanghe.ncdcloud.commission.testApollo:123}"));
        System.out.println(resolveExpression(app.getBeanFactory(), "${ncdcloud.app.build.time:123}"));
        System.out.println(resolveExpression(app.getBeanFactory(), "#{userService.count()}"));
        System.out.println(resolveExpression(app.getBeanFactory(), "#{userService.max(${app.size:12})}"));
        System.out.println(resolveExpression(app.getBeanFactory(), "#{${app.size:12} <= '12345'.length() ? ${app.size:12} : '12345'.length()}"));
        try {
            Thread.sleep(30 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //實現@Value的功能
        System.out.println(resolveExpression(app.getBeanFactory(), "${kanghe.ncdcloud.commission.testApollo:123}"));
        System.out.println("--------------------測試@Value結束---------------------");
    }

    private static final BeanExpressionResolver resolver = new StandardBeanExpressionResolver();

    /**
     * 解析一個表達式,獲取一個值
     *
     * @param beanFactory
     * @param value       一個固定值或一個表達式。如果是一個固定值,則直接返回固定值,否則解析一個表達式,返回解析後的值
     * @return
     */
    public static Object resolveExpression(ConfigurableBeanFactory beanFactory, String value) {
        String resolvedValue = beanFactory.resolveEmbeddedValue(value);

        if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) {
            return resolvedValue;
        }

        return resolver.evaluate(resolvedValue, new BeanExpressionContext(beanFactory, null));
    }
}
/**
 * 測試Bean
 */
@Service("userService")
class UserService {

    public int count() {
        return 10;
    }

    public int max(int size) {
        int count = count();
        return count > size ? count : size;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章