只需要社区评估的东西。以下是代码段,它是一个创建特定类型的实例的简单工厂。该方法将在上下文中将bean注册为原型并返回实例。这是我第一次在运行时配置bean。你能否评价并提供反馈?先谢谢你。
package au.com.flexcontacts.flexoperations;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;
import au.com.flexcontacts.exceptions.SyncClassCreactionError;
/**
* @author khushroo.mistry
* Class purpose: Simple Factory to create an
* instance of SynchroniseContactsService and register it in the Spring IoC.
*/
public final class FLEXSyncFactory implements ApplicationContextAware {
private static AbstractApplicationContext context;
/**
* @param username
* @param password
* @param syncType
* @return the correct service class
* @throws SyncClassCreactionError
* The method registers the classes dynamically into the Spring IoC
*/
public final SynchroniseContactsService createSyncService(String username, String password, SyncType syncType) throws SyncClassCreactionError {
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
try {
//Register the bean in the IoC
BeanDefinition bdb = new GenericBeanDefinition();
bdb.setBeanClassName(syncType.getClassName());
bdb.setScope("prototype");
ConstructorArgumentValues constructor = bdb.getConstructorArgumentValues();
constructor.addIndexedArgumentValue(0, username);
constructor.addIndexedArgumentValue(1, password);
beanFactory.registerBeanDefinition(syncType.getInstanceName(), bdb);
//Return instance of bean
return (SynchroniseContactsService) beanFactory.getBean(syncType.getInstanceName());
} catch (Exception e) {
e.printStackTrace();
throw new SyncClassCreactionError("Error: Illegal Handler");
}
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
context = (AbstractApplicationContext) applicationContext;
}
}
FLEX Sync工厂已经在IoC容器中配置为单例。所以要创建一个新的同步管理器我做以下:
flexSyncFactory.createSyncService(userName, password, SyncType.FULL);
我使用的是Spring 3.1。请检查并提供您宝贵的意见。
亲切的问候。