读书人

spring 经过工厂来创建bean

发布时间: 2012-09-03 09:48:39 作者: rapoo

spring 通过工厂来创建bean
1: 这个例子中我们使用工厂模式来取的bean。首先我们来获取context

public class SpringContextSupport implements ServletContextAware {

private static Object initObj = null;

private static int count = 0;

private static ApplicationContext context;

public static void init(Object o) {
initObj = o;
count++;
}

/**
*
* gets the instance from the beanId
*
* @param object
* @return void
*/
public static Object getBean(String beanName) {
return getApplicationContext().getBean(beanName);
}

/**
*
* returns applicationContext based on initObj
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
if (initObj == null) {
throw new IllegalStateException(
"Application context not initialized");
} else if (initObj instanceof ServletContext) {
ServletContext servletContext = (ServletContext) initObj;
return WebApplicationContextUtils
.getRequiredWebApplicationContext(servletContext);

} else if (initObj instanceof String) {
if (context == null) {
context = new FileSystemXmlApplicationContext(
Constants.FILE_CONTEXT_PATH);
}
return context;
} else {
throw new IllegalStateException(
"You must initialize the context with a String");
}
}

/**
*
* initializes servletContext
*
* @param context
* @return void
*/
public void setServletContext(ServletContext context) {
init(context);
}

public static void initializeStandalone() {
init("StandAlone");
}


/**
*
* initializes servletContext for bid board batch
*
* @param context
* @return void
*/
public static void initBidBoardBatch() {
init( Constants.BB_BATCH_STARTUP);
}
}

备注: String FILE_CONTEXT_PATH = "WEB-INF/conf/user-services.xml";
那么在这个文件中就是我们配置的bean
2: 具体通过工厂是方法来取得我们所需要的bean
public class DAOFactory {
public UserDAO getUserDAO() throws Exception {
UserDAO userDAO = null;
try {
userDAO = (UserDAO) SpringContextSupport
.getBean(DAOConstants.USER_DAO);
} catch (Exception exception) {
throw exception;
}
return userDAO;
}
}

3: 那么我们想对应的service工厂模式的创建也类似:如下:
public class CommonServiceFactory {
public CommonService getCommonService() throws BBSystemException {
CommonService commonService = null;

commonService =
(CommonService) SpringContextSupport
.getBean(BBServiceConstants.COMMON_SERVICE);

if (null == commonService) {
throw BBUtil.getBBSystemException(BBMessageConstants.OBJECTS_NULL);
}
return commonService;
}
}

读书人网 >软件架构设计

热点推荐