【Spring】bean動態註冊到spring
/*
* http://412887952-qq-com.iteye.com/blog/2348445
* http://www.jb51.net/article/106558.htm
* https://my.oschina.net/xiaominmin/blog/1607747
*/
public void loadProtoResources() throws IOException, ClassNotFoundException {
Resource[] resources = null;
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String protoPackage = grpcLocalProxyProperties.getDescriptorSet();
String protoClasspath = protoPackage.replace(".", "/");
resources = resolver.getResources(protoClasspath + "/*Proto.class");
ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)context.getBeanFactory();
for (Resource resource : resources) {
String className = resource.getFilename().split("\\.")[0];
String fullClassName = protoPackage + "." + className;
Class<?> cls = Class.forName(fullClassName);
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(cls);
// beanDefinitionBuilder.addPropertyValue("someKey","someValue");
assert fullClassName.equals(cls.getName());
beanFactory.registerBeanDefinition(cls.getName(), beanDefinitionBuilder.getBeanDefinition());
protoBeans.add(fullClassName);
}
protoBeans.stream().forEach(protoBean -> LOG.info("Registered protoBeans: {}", protoBean));
}
/* * http://412887952-qq-com.iteye.com/blog/2348445 * http://www.jb51.net/article/106558.htm * https://my.oschina.net/xiaominmin/blog/1607747 */ public void loadProtoResources() throws IOException, ClassNotFoundException { Resource[] resources = null; PathMatchingResourcePatternResolver resolver= new PathMatchingResourcePatternResolver(); String protoPackage = grpcLocalProxyProperties.getDescriptorSet(); String protoClasspath = protoPackage.replace(".", "/"); resources = resolver.getResources(protoClasspath + "/*Proto.class"); ConfigurableApplicationContext context= (ConfigurableApplicationContext)applicationContext; DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)context.getBeanFactory(); for (Resource resource : resources) { String className = resource.getFilename().split("\\.")[0]; String fullClassName = protoPackage + "." + className; Class<?> cls = Class.forName(fullClassName); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(cls); // beanDefinitionBuilder.addPropertyValue("someKey","someValue"); assert fullClassName.equals(cls.getName()); beanFactory.registerBeanDefinition(cls.getName(), beanDefinitionBuilder.getBeanDefinition()); protoBeans.add(fullClassName); } protoBeans.stream().forEach(protoBean -> LOG.info("Registered protoBeans: {}", protoBean)); }