您可以使用GenericApplicationContext将 bean 与在 xml 中声明的其余 spring bean 一起动态加载到 applicationContext。这是使用反射库实现的示例...
private static final Pattern SERVICE_UTIL_PATTERN = Pattern.compile(".*LocalServiceUtil.*");
public static void main(String[] args) {
ConfigurationBuilder builder = new ConfigurationBuilder().addUrls(
ClasspathHelper.forPackage("x.y.z"))
.setScanners(new SubTypesScanner(false));
Reflections reflections = new Reflections(builder);
GenericApplicationContext applicationContext = new GenericApplicationContext();
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);
for (Class<? extends Object> serviceUtilClass : classes) {
String className = serviceUtilClass.getName();
if (SERVICE_UTIL_PATTERN.matcher(className).matches()) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClassName(className);
beanDefinition.setFactoryMethodName("getService");
beanDefinition.setLazyInit(true);
String beanName = StringUtils.uncapitalize(serviceClass.getSimpleName().replace("Util", ""));
applicationContext.registerBeanDefinition(beanName, beanDefinition);
}
}
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);
reader.loadBeanDefinitions("classpath:/applicationContext.xml");
applicationContext.refresh();
}
更新: 要在 Web 应用程序中使用它,您可以简单地扩展 Spring 的XmlWebApplicationContext并覆盖该initBeanDefinitionReader
方法,如下所示...
private static final Pattern SERVICE_UTIL_PATTERN = Pattern.compile(".*LocalServiceUtil.*");
@Override
protected void initBeanDefinitionReader(
XmlBeanDefinitionReader beanDefinitionReader) {
ConfigurationBuilder builder = new ConfigurationBuilder().addUrls(
ClasspathHelper.forPackage("x.y.z"))
.setScanners(new SubTypesScanner(false));
Reflections reflections = new Reflections(builder);
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);
BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
for (Class<? extends Object> serviceClass : classes) {
String className = serviceClass.getName();
if (SERVICE_UTIL_PATTERN.matcher(className).matches()) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClassName(className);
beanDefinition.setFactoryMethodName("getService");
beanDefinition.setLazyInit(true);
String beanName = StringUtils.uncapitalize(serviceClass
.getSimpleName().replace("Util", ""));
registry.registerBeanDefinition(beanName, beanDefinition);
}
}
}
}
并将以下内容添加context-param
到您的web.xml ...
<context-param>
<param-name>contextClass</param-name>
<param-value>x.y.z.MyXmlWebApplicationContext</param-value>
</context-param>