文章目录
前言
记录工作中用到的一些不算常用但是比较有用的代码
一、ClassLoader类使用
代码示例:
public class MoudleClassLoader {
private static final Method METHOD_DEFONECLASS;
/**
* 类加载器
*/
private static final SecureClassLoader SECURE_CLASS_LOADER;
static{
try {
METHOD_DEFINECLASS = ClassLoader.class.getDeclaredMethod("defineClass",byte[].class,int.class,int.class);
METHOD_DEFINECLASS.setAccessible(true);
SECURE_CLASS_LOADER = (SecureClassLoader) Thread.CurrentThread().getContextClassLoader();
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
...
//获取到类名和对应类的字节流
String methodName;
byte[] byte;
try {
//加载字节流到jvm
METHOD_DEFINECLASS.invoke(SECURE_CLASS_LOADER, byte,0,byte.length);
Class<?> aClass = SECURE_CLASS_LOADER.loadClass(methodName)
} catch (Exception illegalAccessException) {
e.printStackTrace();
}
}
二、将类加入ioc容器
1.实现BeanFactoryPostProcessor接口
代码如下(示例):
@Component
class Test implements BeanFactoryPostProcessor{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeanException {
DefaultListableBeanFactory defaultListableBeanFactory =(DefaultListableBeanFactory) beanFactory;
defaultListableBeanFactory.registerBeanDefinition("类名",new RootBeanDefinition(class类(xxx.class)));
}
}
2.实现BeanDefinitionRegistryPostProcessor接口
代码如下(示例):
@Component
class TestBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
beanDefinitionRegistry.registerBeanDefinition("类名",new RootBeanDefinition(class类(xxx.class)));
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
//同上
}
}
三、获取配置参数工具类
@Component
public class Utils {
private static Environment environment;
@Autowired
public void setEnvironment(){
Utils.environment = environment;
}
public static String getProperty(String key){
return environment.getProperty(key);
}
}
四、从srping上下文根据类型获取bean
@Component
public class SpringContextUtils implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz){
return applicatonContext.getBean(clazz);
}
}