准备bean
static class Bean1 {
@Value("${JAVA_HOME}")
private String javaHome;
@Value("30")
private int age;
}
static class Bean2 {
@Value("#{@bean3}")
private Bean3 bean3;
}
@Component("bean3")
static class Bean3 {
}
static class Bean4 {
@Value("#{'hello, ' + '${JAVA_HOME}'}")
private String helloJavaHome;
}
解析
@SneakyThrows
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestValue.class);
DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory();
ContextAnnotationAutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver();
resolver.setBeanFactory(beanFactory);
resolve(applicationContext, resolver, Bean4.class.getDeclaredField("helloJavaHome"));
}
private static void resolve(AnnotationConfigApplicationContext applicationContext, ContextAnnotationAutowireCandidateResolver resolver, Field field) {
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(field, true);
String originValue = resolver.getSuggestedValue(dependencyDescriptor).toString();
System.out.println("originValue = " + originValue);
String resolvedPlaceholders = applicationContext.getEnvironment().resolvePlaceholders(originValue);
System.out.println("resolvedPlaceholders = " + resolvedPlaceholders);
ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
Object ret = beanFactory.getBeanExpressionResolver().evaluate(resolvedPlaceholders, new BeanExpressionContext(beanFactory, null));
System.out.println("ret = " + ret);
System.out.println("ret.getClass() = " + ret.getClass());
ret = beanFactory.getTypeConverter().convertIfNecessary(ret, dependencyDescriptor.getDependencyType());
System.out.println("ret = " + ret);
System.out.println("ret.getClass() = " + ret.getClass());
}