* switched to @FactoryBean@ based implementation to create @PluginRegistry@ instances from the namespace

git-svn-id: svn+ssh://svn.synyx.de/var/svn/synyx/opensource/hera/trunk@5402 5a64d73e-33d6-4ccc-9058-23f8668ecac9
This commit is contained in:
Oliver Gierke
2009-04-21 14:51:14 +00:00
parent a9eff35651
commit 522a66e535
10 changed files with 220 additions and 502 deletions

View File

@@ -1,66 +0,0 @@
package org.synyx.hera.core.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.BeanReference;
/**
* {@link BeanPostProcessor} to handle {@link BeanReference} beans and replacing
* it by its reference target.
*
* @author Oliver Gierke - gierke@synyx.de
*/
public class BeanReferenceBeanPostProcessor implements BeanPostProcessor,
BeanFactoryAware {
private BeanFactory beanFactory;
/*
* (non-Javadoc)
*
* @see
* org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org
* .springframework.beans.factory.BeanFactory)
*/
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
/*
* (non-Javadoc)
*
* @seeorg.springframework.beans.factory.config.BeanPostProcessor#
* postProcessAfterInitialization(java.lang.Object, java.lang.String)
*/
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
// Skip non RuntimeBeanReferences
if (!(bean instanceof BeanReference)) {
return bean;
}
BeanReference reference = (BeanReference) bean;
return beanFactory.getBean(reference.getBeanName());
}
/*
* (non-Javadoc)
*
* @seeorg.springframework.beans.factory.config.BeanPostProcessor#
* postProcessBeforeInitialization(java.lang.Object, java.lang.String)
*/
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
}

View File

@@ -15,17 +15,11 @@
*/
package org.synyx.hera.core.config;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.RuntimeBeanNameReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
@@ -48,7 +42,7 @@ public class PluginListDefinitionParser extends AbstractBeanDefinitionParser {
*/
protected String getPostProcessorName() {
return PACKAGE + "BeanListBeanFactoryPostProcessor";
return PACKAGE + "BeanListFactoryBean";
}
@@ -63,115 +57,10 @@ public class PluginListDefinitionParser extends AbstractBeanDefinitionParser {
protected AbstractBeanDefinition parseInternal(Element element,
ParserContext context) {
if (context.isNested()) {
return parseNested(element, context);
} else {
return parseStandalone(element, context);
}
}
/**
* Parses a nested {@code <list />} or {@code <registry />} element.
* Registers the {@link BeanFactoryPostProcessor} as in standalone mode but
* returns a reference to the list or registry created by instead of the
* {@link BeanFactoryPostProcessor} itself.
*
* @param element
* @param context
* @return
*/
private AbstractBeanDefinition parseNested(Element element,
ParserContext context) {
// Step 1 - Create reference wrapped in a bean definition
BeanDefinitionBuilder builder =
BeanDefinitionBuilder
.genericBeanDefinition(RuntimeBeanNameReference.class
.getName());
// Extract id attribute from element or generate custom one
String idAttribute = element.getAttribute("id");
String listId =
StringUtils.hasText(idAttribute) ? idAttribute
: BeanDefinitionReaderUtils.generateBeanName(builder
.getBeanDefinition(), context.getRegistry(),
true);
// Let reference point to the bean with the calculated id
builder.addConstructorArgValue(listId);
// Step 2 - Register BeanPostProcessor to unwrap the reference
registerReferenceResolver(element, context);
// Step 3 - Set the id to let the BeanFactoryPostProcessor (BFPP)
// register the list as reference target
element.setAttribute("id", listId);
// Step 4 - Register BFPP ourselves
AbstractBeanDefinition definition = parseStandalone(element, context);
String beanFactoryxPostProcessorId =
resolveId(element, definition, context);
BeanDefinitionHolder holder =
new BeanDefinitionHolder(definition,
beanFactoryxPostProcessorId);
registerBeanDefinition(holder, context.getRegistry());
// Step 5 - Return the reference to the list created by the BFPP
return getSourcedBeanDefinition(builder, element, context);
}
/**
* Registers a {@link BeanReferenceBeanPostProcessor} to automatically
* unwrap {@link BeanDefinition}s that contain a reference to other beans.
*
* @param element
* @param context
*/
private void registerReferenceResolver(Element element,
ParserContext context) {
BeanDefinitionBuilder builder =
BeanDefinitionBuilder
.genericBeanDefinition(BeanReferenceBeanPostProcessor.class);
BeanDefinition definition =
getSourcedBeanDefinition(builder, element, context);
registerBeanDefinition(new BeanDefinitionHolder(definition, generateId(
definition, context)), context.getRegistry());
}
/**
* Parses a standalone {@code <list />} or {@code <registry />} element and
* registers a {@link BeanFactoryPostProcessor} to automatically register
* all beans of the type specified in {@code class} property under the given
* id.
*
* @param element
* @param context
* @return
*/
@SuppressWarnings("unchecked")
private AbstractBeanDefinition parseStandalone(Element element,
ParserContext context) {
ManagedMap map = new ManagedMap();
map.put(element.getAttribute("id"), element.getAttribute("class"));
BeanDefinitionBuilder builder =
BeanDefinitionBuilder
.genericBeanDefinition(getPostProcessorName());
builder.addPropertyValue("lists", map);
String initFactories = element.getAttribute("init-factories");
if (StringUtils.hasText(initFactories)) {
builder.addPropertyValue("initFactories", initFactories);
}
builder.addPropertyValue("type", element.getAttribute("class"));
return getSourcedBeanDefinition(builder, element, context);
}
@@ -196,27 +85,14 @@ public class PluginListDefinitionParser extends AbstractBeanDefinitionParser {
}
/**
* Generates a custom id for the given {@link BeanDefinition}.
*
* @param definition
* @param context
* @return
*/
private String generateId(BeanDefinition definition, ParserContext context) {
return context.getReaderContext().generateBeanName(definition);
}
/*
* (non-Javadoc)
*
* @seeorg.springframework.beans.factory.xml.AbstractBeanDefinitionParser#
* shouldGenerateId()
* shouldGenerateIdAsFallback()
*/
@Override
protected boolean shouldGenerateId() {
protected boolean shouldGenerateIdAsFallback() {
return true;
}

View File

@@ -33,6 +33,6 @@ public class PluginRegistryDefinitionParser extends PluginListDefinitionParser {
@Override
protected String getPostProcessorName() {
return PACKAGE + "PluginRegistryBeanFactoryPostProcessor";
return PACKAGE + "PluginRegistryFactoryBean";
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.synyx.hera.core.support;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Abstract base class to implement types that need access to all beans of a
* given type from the {@link ApplicationContext}.
*
* @author Oliver Gierke - gierke@synyx.de
*/
public abstract class AbstractTypeAwareSupport<T> implements
ApplicationContextAware {
private ApplicationContext context;
private Class<T> type;
/*
* (non-Javadoc)
*
* @see
* org.springframework.context.ApplicationContextAware#setApplicationContext
* (org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
/**
* @param type the type to set
*/
public void setType(Class<T> type) {
this.type = type;
}
/**
* Returns all beans from the {@link ApplicationContext} that match the
* given type.
*
* @return
*/
protected List<T> getBeans() {
@SuppressWarnings("unchecked")
Map<String, T> pluginMap = context.getBeansOfType(type);
return new ArrayList<T>(pluginMap.values());
}
}

View File

@@ -1,245 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.synyx.hera.core.support;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.ListFactoryBean;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.core.Ordered;
import org.synyx.hera.core.SimplePluginRegistry;
/**
* Simple {@link BeanFactoryPostProcessor} to autocreate lists of the configured
* {@code lists} property. The post processor will register
* {@link ListFactoryBean}s for each list named with the given key containing
* all beans of the {@link org.springframework.context.ApplicationContext}
* implementing the interface defines as lists value. E.g.:
*
* <pre>
* &lt;bean class=&quot;org.synyx.plugin.core.support.BeanListFactoryPostProcessor&quot;&gt;
* &lt;property name=&quot;lists&quot;&gt;
* &lt;map&gt;
* &lt;entry key=&quot;beanName&quot; value=&quot;org.synyx.plugin.core.Plugin&quot; /&gt;
* &lt;/map&gt;
* &lt;/property&gt;
* &lt;/bean&gt;
* </pre>
*
* This would register all Spring beans implementing the
* {@link org.synyx.hera.core.Plugin} interface in a list bean with the name
* {@coder beanName}.
*
* @author Oliver Gierke - gierke@synyx.de
*/
public class BeanListBeanFactoryPostProcessor implements
BeanFactoryPostProcessor, Ordered {
private static final Log log =
LogFactory.getLog(BeanListBeanFactoryPostProcessor.class);
private Map<String, Class<?>> lists = new HashMap<String, Class<?>>();
private boolean initFactories = false;
/**
* Setter to inject required plugin registry configuration. The map's keys
* will be used as bean ids for the resulting {@link SimplePluginRegistry}
* instances. These registry instances will contain all beans having the
* given type.
*
* @param registryMap
*/
public void setLists(Map<String, Class<?>> lists) {
this.lists = lists;
}
/**
* Setter to activate {@link org.springframework.beans.factory.FactoryBean}
* scanning. This allows auto-registration of factory bean targets (the
* objects actually created by the factory bean} but comes with the drawback
* of having to initialize those factories eagerly. This can cause
* unpredictable behaviour if other {@link BeanFactoryPostProcessor}s would
* have been applied to these factories. Defaults to {@value #initFactories}
* .
*
* @param initFactories the allowEagerInit to set
*/
public void setInitFactories(boolean initFactories) {
this.initFactories = initFactories;
}
/*
* (non-Javadoc)
*
* @seeorg.springframework.beans.factory.config.BeanFactoryPostProcessor#
* postProcessBeanFactory
* (org.springframework.beans.factory.config.ConfigurableListableBeanFactory
* )
*/
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (!(beanFactory instanceof BeanDefinitionRegistry)) {
throw new IllegalArgumentException(
"Given beanFactory is not a BeanDefinitionRegistry!");
}
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// Do for each required wrapper
for (String wrapperName : lists.keySet()) {
Class<?> requiredType = lists.get(wrapperName);
// Find implementations of the component type
List<RuntimeBeanReference> beans =
getBeanReferencesOfType(beanFactory, requiredType);
registerListBeanDefinition(wrapperName, requiredType, beans,
registry);
}
}
/**
* Registers a {@link ListFactoryBean} containing the given beans under the
* given id. Allows subclasses to modify or wrap the actually registered
* bean definition by calling
* {@link #wrapListBeanDefinition(BeanDefinition)} with the bean definition
* of the {<7B>linl {@link ListFactoryBean}.
*
* @param id
* @param beans
* @param registry
*/
protected <T> void registerListBeanDefinition(String id, Class<T> type,
List<RuntimeBeanReference> beans, BeanDefinitionRegistry registry) {
// Create ListFactory bean definition
BeanDefinitionBuilder listDefinitionBuilder =
BeanDefinitionBuilder.rootBeanDefinition(ListFactoryBean.class);
// Set the implementations as source for the wrapper
listDefinitionBuilder.addPropertyValue("sourceList", beans);
BeanDefinition beanDefinition =
wrapListBeanDefinition(getSourcedBeanDefinition(listDefinitionBuilder));
if (log.isDebugEnabled()) {
log.debug(String.format(
"Registering bean '%s' of type %s containing %s!", id,
beanDefinition.getBeanClassName(), beans.toString()));
}
// Register wrapper under defined name
registry.registerBeanDefinition(id, beanDefinition);
}
/**
* Template method to allow subclasses to wrap the list bean definition into
* another bean definition that will actually be registered. The default
* implementation simply returns the given bean definition.
*
* @param beanDefinition
* @return
*/
protected BeanDefinition wrapListBeanDefinition(
BeanDefinition beanDefinition) {
return beanDefinition;
}
/**
* Returns a {@link BeanDefinitionBuilder}s {@link BeanDefinition} setting
* the current {@link PluginRegistryBeanFactoryPostProcessor} as source.
*
* @param builder
* @return
*/
protected BeanDefinition getSourcedBeanDefinition(
BeanDefinitionBuilder builder) {
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
beanDefinition.setSource(this);
return beanDefinition;
}
/**
* Returns bean references to beans with the given type.
*
* @param beanFactory
* @param type
* @return
*/
@SuppressWarnings("unchecked")
protected List<RuntimeBeanReference> getBeanReferencesOfType(
ConfigurableListableBeanFactory beanFactory, Class<?> type) {
// Lookup bean candidates either via Spring or manually
List<String> beanNames =
Arrays.asList(beanFactory.getBeanNamesForType(type, true,
initFactories));
List<RuntimeBeanReference> beanReferences =
new ManagedList(beanNames.size());
for (String beanName : beanNames) {
RuntimeBeanReference reference = new RuntimeBeanReference(beanName);
reference.setSource(this);
beanReferences.add(reference);
}
return (List<RuntimeBeanReference>) beanReferences;
}
/**
* Declare lowest precedence to ensure all other
* {@link BeanFactoryPostProcessor}s have already been applied.
*
* @see org.springframework.core.Ordered#getOrder()
*/
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.synyx.hera.core.support;
import java.awt.List;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
/**
* Factory to create bean lists for a given type. Exposes all beans of the
* configured type that can be found in the {@link ApplicationContext}.
*
* @author Oliver Gierke - gierke@synyx.de
*/
public class BeanListFactoryBean<T> extends AbstractTypeAwareSupport<T>
implements FactoryBean {
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
public Object getObject() throws Exception {
return getBeans();
}
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@SuppressWarnings("unchecked")
public Class getObjectType() {
return List.class;
}
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
*/
public boolean isSingleton() {
return true;
}
}

View File

@@ -1,60 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.synyx.hera.core.support;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.synyx.hera.core.OrderAwarePluginRegistry;
/**
* This {@link BeanFactoryPostProcessor} automatically looksup bean instances
* from the {@link BeanFactory} hierarchy and registers
* {@link OrderAwarePluginRegistry} instances for them.
*
* @see org.synyx.hera.core.support.BeanListBeanFactoryPostProcessor
* @author Oliver Gierke - gierke@synyx.de
*/
public class PluginRegistryBeanFactoryPostProcessor extends
BeanListBeanFactoryPostProcessor {
/**
* Additionally wraps the
* {@link org.springframework.beans.factory.config.ListFactoryBean}
* {@link BeanDefinition} into a {@link OrderAwarePluginRegistry}.
*
* @see com.synyx.minos.core.plugin.support.BeanListBeanFactoryPostProcessor#
* wrapBeanDefinition
* (org.springframework.beans.factory.config.BeanDefinition)
* @return a {@link BeanDefinition} containing a
* {@link OrderAwarePluginRegistry}
*/
@Override
protected BeanDefinition wrapListBeanDefinition(
BeanDefinition beanDefinition) {
// Create PluginRegistry bean definition to wrap actual bean definition
BeanDefinitionBuilder builder =
BeanDefinitionBuilder
.rootBeanDefinition(OrderAwarePluginRegistry.class);
builder.addPropertyValue("plugins", beanDefinition);
return getSourcedBeanDefinition(builder);
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.synyx.hera.core.support;
import org.springframework.beans.factory.FactoryBean;
import org.synyx.hera.core.OrderAwarePluginRegistry;
import org.synyx.hera.core.Plugin;
import org.synyx.hera.core.PluginRegistry;
/**
* {@link FactoryBean} to create {@link PluginRegistry} instances. Wraps a
* {@link BeanListFactoryBean}.
*
* @author Oliver Gierke - gierke@synyx.de
*/
public class PluginRegistryFactoryBean<T extends Plugin<S>, S> extends
AbstractTypeAwareSupport<T> implements FactoryBean {
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
public Object getObject() throws Exception {
return OrderAwarePluginRegistry.create(getBeans());
}
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@SuppressWarnings("unchecked")
public Class getObjectType() {
return PluginRegistry.class;
}
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
*/
public boolean isSingleton() {
return true;
}
}

View File

@@ -39,11 +39,19 @@ public class PluginConfigurationIntegrationTest {
@Qualifier("otherHost")
SamplePluginHost otherHost;
@Autowired
SamplePlugin plugin;
@Test
public void test() throws Exception {
assertNotNull(samplePlugins);
assertSame(pluginRegistry, host.getRegistry());
assertNotSame(pluginRegistry, otherHost.getRegistry());
assertTrue(samplePlugins.contains(plugin));
assertTrue(pluginRegistry.contains(plugin));
}
}

View File

@@ -14,8 +14,7 @@
<bean id="host" class="org.synyx.hera.core.SamplePluginHost">
<property name="registry" ref="bar" />
</bean>
<!-- Uncommented till TODO in PluginListDefinitionParser is resolved -->
<bean id="otherHost" class="org.synyx.hera.core.SamplePluginHost">
<property name="registry">
<plugin:registry id="tadaa" class="org.synyx.hera.core.SamplePlugin" />