220715工作代码记录(自用)


前言

记录工作中用到的一些不算常用但是比较有用的代码

一、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);
}

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值