0

I'm using xml-based Spring bean configuration. For certain beans, I want to dynamically load the classes based on the different configs. (I could create a parent class for those classes)

Currently I have a workaround solution:

  1. use of system property tag to dynamically load the class

:

<bean id="dynamicBean" class="com.xyz.${MODEL}MyBeanClass"/>

where MyBean classes are created under different package names, and ${MODEL} will be set to the corresponding package name e.g. "mypackage." at runtime.

The above solution works fine, but I don't see this as a common practice to dynamically initialize a bean in xml-base spring config.

Any cons for this method? and more importantly, what are the alternative ways of achieving the same.

4

1 回答 1

1

使用 FactoryBean

<bean class="ClzInitFactoryBean">
    <property name="clz" value="com.xyz.${MODEL}MyBeanClass" />
</bean>

ClzInitFactoryBean.java

public class ClzInitFactoryBean implements FactoryBean {
    public void setClz(String clz) throws ClassNotFoundException {
        clazz = Class.forName(clz);
    }

    private String clz;
    private Class<?> clazz;

    public Object getObject() throws Exception {
        return BeanUtils.instantiateClass(clazz);
    }

    public Class getObjectType() {
        return clazz;
    }

    public boolean isSingleton() {
        return false;
    }
}
于 2013-11-06T07:17:18.967 回答