java bean prototype_java – 在Spring中运行时注册bean(prototype)

只需要社区评估的东西。以下是代码段,它是一个创建特定类型的实例的简单工厂。该方法将在上下文中将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。请检查并提供您宝贵的意见。

亲切的问候。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值