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.

1 Answer 1

1

Use a 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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.