不廢話,直接上代碼,實測有效
@Component
public class StaticValueSupport {
@Autowired
public void init(ApplicationContext context) throws IllegalAccessException {
AutowiredAnnotationBeanPostProcessor factory = context.getBean(AutowiredAnnotationBeanPostProcessor.class);
ConfigurableListableBeanFactory beanFactory = (ConfigurableListableBeanFactory) FieldUtils
.readDeclaredField(factory, "beanFactory", true);
Environment env = context.getEnvironment();
String[] beanDeintitNames = context.getBeanDefinitionNames();
for (String name : beanDeintitNames) {
Object obj = context.getBean(name);
Field[] field = FieldUtils.getAllFields(obj.getClass());
for (Field f : field) {
if (f.isAnnotationPresent(Value.class) && Modifier.isStatic(f.getModifiers())) {
String value = f.getAnnotation(Value.class).value();
String reValue = env.resolvePlaceholders(value);
FieldUtils.writeStaticField(f,
beanFactory.getTypeConverter().convertIfNecessary(reValue, f.getType()));
}
}
}
}
}