All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.common.util.BeanUtils Maven / Gradle / Ivy

The newest version!
/**
 * Copyright 2011-2012 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.sf.common.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.naming.NameAlreadyBoundException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractRefreshableConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @author Steve M. Jung
 * @since 2011. 6. 2. (version 0.0.1)
 */
public class BeanUtils implements ApplicationContextAware, InitializingBean {
	private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

	private static Map beanUtilsCache = new ConcurrentHashMap();
	/**
	 * Get a BeanUtils instance by applicationContextName.
* In case of webapp, applicationContextName may be the contextPath. * * @param applicationContextName * @return A BeanUtils instance */ public static BeanUtils getInstance(String applicationContextName) { return beanUtilsCache.get(applicationContextName); } private String applicationContextName; public String getApplicationContextName() { return applicationContextName; } public void setApplicationContextName(final String applicationContextName) throws NameAlreadyBoundException { ValueUtils.assertNotNull("applicationContextName", applicationContextName); String monName = "BeanUtils.beanUtils." + applicationContextName; synchronized (SyncCtrlUtils.get(monName)) { try { if (beanUtilsCache.containsKey(applicationContextName)) { if (beanUtilsCache.get(applicationContextName).equals(this)) return; throw new NameAlreadyBoundException("already bounded application context name: " + applicationContextName); } this.applicationContextName = applicationContextName; beanUtilsCache.put(applicationContextName, this); } finally { SyncCtrlUtils.release(monName); } } } /** * Get a singletone spring bean by requiredType.
* If the bean does not exist, it'll be created and registered. * *
	 * beanUtils.get(TestService.class).execute(vo);
	 * 
* * @param clazz * @return A singletone spring bean */ public T get(Class clazz) { return get(clazz, clazz); } private Map, Object> beanByClassCache = new ConcurrentHashMap, Object>(); /** * Get a singletone spring bean by clazz and requiredType.
* If the bean does not exist, it'll be created and registered. * * @param clazz * @param requiredType * @return A singletone spring bean */ @SuppressWarnings("unchecked") public T get(final Class clazz, final Class requiredType) { ValueUtils.assertNotNull("clazz", clazz); ValueUtils.assertNotNull("requiredType", requiredType); final boolean debug = logger.isDebugEnabled(); T bean; if (beanByClassCache.containsKey(clazz)) { if (debug) logger.debug("get bean from beanByClassCache by class: " + clazz.getName()); bean = (T) beanByClassCache.get(clazz); } else { bean = (T) SyncCtrlUtils.wrap("BeanUtils.beanByClass." + clazz.getSimpleName(), beanByClassCache, clazz, new Closure() { public Object execute() { try { if (debug) logger.debug("try to get bean from applicationContext by class: " + clazz.getName()); return applicationContext.getBean(clazz); } catch (BeansException e) { try { if (debug) logger.debug("try to get bean from applicationContext by className: " + clazz.getName()); return applicationContext.getBean(clazz.getName(), requiredType); } catch (NoSuchBeanDefinitionException e1) { if (debug) logger.debug("register bean from applicationContext by class: " + clazz.getName()); register(clazz); if (debug) logger.debug("retry to get bean from applicationContext by className: " + clazz.getName()); return applicationContext.getBean(clazz.getName(), requiredType); } } } }); } if (!requiredType.isAssignableFrom(bean.getClass())) throw new BeanNotOfRequiredTypeException(bean.getClass().getName(), requiredType, bean.getClass()); return bean; } private void register(Class clazz) { if (this.applicationContext instanceof AbstractRefreshableConfigApplicationContext) { BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(clazz).getBeanDefinition(); AbstractRefreshableConfigApplicationContext ac = (AbstractRefreshableConfigApplicationContext) this.applicationContext; DefaultListableBeanFactory bf = (DefaultListableBeanFactory) ac.getBeanFactory(); bf.registerBeanDefinition(clazz.getName(), beanDefinition); } else if (this.applicationContext instanceof GenericApplicationContext) { BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(clazz).getBeanDefinition(); GenericApplicationContext ac = (GenericApplicationContext) this.applicationContext; ac.registerBeanDefinition(clazz.getName(), beanDefinition); } else { throw new NoSuchBeanDefinitionException(clazz); } } private Map beanByNameCache = new ConcurrentHashMap(); /** * Get a singletone spring bean by name. * *
	 * ((TestService) beanUtils.get("testService")).execute(vo);
	 * 
* * @param name * @return A singletone spring bean */ public Object get(final String name) { ValueUtils.assertNotNull("name", name); final boolean debug = logger.isDebugEnabled(); if (beanByNameCache.containsKey(name)) { if (debug) logger.debug("get bean from beanByNameCache by name: " + name); return beanByNameCache.get(name); } return SyncCtrlUtils.wrap("BeanUtils.beanByName." + name, beanByNameCache, name, new Closure() { public Object execute() { if (debug) logger.debug("try to get bean from applicationContext by name: " + name); return applicationContext.getBean(name); } }); } /** * Get a singletone spring bean by name and requiredType. * *
	 * beanUtils.get("testService", TestService.class).execute(vo);
	 * 
* * @param name * @param requiredType * @return A singletone spring bean */ @SuppressWarnings("unchecked") public T get(final String name, final Class requiredType) { ValueUtils.assertNotNull("name", name); ValueUtils.assertNotNull("requiredType", requiredType); Object bean = get(name); if (!requiredType.isAssignableFrom(bean.getClass())) throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); return (T) bean; } /** * Get bean names by type. * * @param type * @return Bean names */ public String[] getNames(Class type) { return applicationContext.getBeanNamesForType(type); } private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void afterPropertiesSet() throws Exception { if (ValueUtils.isEmpty(getApplicationContextName())) throw new IllegalArgumentException("Property 'applicationContextName' is required."); } public void clear() { logger.info("Clearing beanUtils of applicationContextName: " + applicationContextName + "..."); beanByClassCache.clear(); beanByNameCache.clear(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy