讓Spring boot的@Value支持static屬性的注入

不廢話,直接上代碼,實測有效 


@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()));

				}
			}
		}
	}

}

 

發佈了3 篇原創文章 · 獲贊 0 · 訪問量 2582
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章