Spring中的一些小技巧

初始化类

import org.springframework.util.ClassUtils
import org.springframework.beans.BeanUtils
import org.springframework.util.Assert

Class instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor constructor = instanceClass
        .getDeclaredConstructor(parameterTypes);
T instance = (T) BeanUtils.instantiateClass(constructor, args);

从所有jar文件中获取某个路径的所有文件

Enumeration urls = classLoader.getResources("META-INF/spring.factories"); 或
Enumeration urls = ClassLoader.getSystemResources("META-INF/spring.factories").
while (urls.hasMoreElements()) {
    URL url = urls.nextElement();
    Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
}

将properties中的键值对赋值给targetObject

//将properties文件中的spring.profiles.active=dev赋值给springProfiles中的active属性
//摘自org.springframework.boot.context.config.ConfigFileApplicationListener.Loader.bindSpringProfiles(PropertySources propertySources)

SpringProfiles springProfiles = new SpringProfiles();
RelaxedDataBinder dataBinder = new RelaxedDataBinder(springProfiles,
        "spring.profiles");
dataBinder.bind(new PropertySourcesPropertyValues(propertySources, false));

读取class中所有可写的属性或set方法

org.springframework.beans.BeanUtils.getPropertyDescriptors(Class clazz)
常用于对bean进行赋值

它是对以下jdk自带方法的扩展:
BeanInfo beanInfo= Introspector.getBeanInfo(beanClass);
PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
由于此方法速度较慢,spring的对它扩展的同时加入了缓存功能保证只读取一次

你可能感兴趣的:(spring-boot)