001 /**
002 * Copyright 2004-2012 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.kuali.hr.sys.context;
017
018 import org.kuali.hr.sys.util.constants.SpringBeans;
019 import org.springframework.beans.BeansException;
020 import org.springframework.context.ApplicationContext;
021 import org.springframework.context.ApplicationContextAware;
022
023 /**
024 * helper class for spring beans stuff
025 *
026 * Copied over from SpringContext.java from the LeaveManager Project
027 */
028 public class SpringContext implements ApplicationContextAware {
029
030 private static ApplicationContext applicationContext;
031
032 /**
033 * public constructor that throws exception if you try to instantiate it
034 * twice
035 *
036 * @throws Exception
037 */
038 public SpringContext() throws Exception {
039 if (applicationContext != null)
040 throw new Exception(
041 "Cannot instantiate SpringContext twice. Use the static methods");
042 }
043
044 /*
045 * (non-Javadoc)
046 *
047 * @see
048 * org.springframework.context.ApplicationContextAware#setApplicationContext
049 * (org.springframework.context.ApplicationContext)
050 */
051 @Override
052 public void setApplicationContext(ApplicationContext applicationContext)
053 throws BeansException {
054 SpringContext.applicationContext = applicationContext;
055 }
056
057 /**
058 * return a spring bean by its name
059 *
060 * @param beanName
061 * @return
062 */
063 public static Object getBean(SpringBeans bean) {
064 return applicationContext.getBean(bean.toString());
065 }
066
067 /**
068 * returns a spring bean by its class... this only works when the class name
069 * equals the spring bean name
070 *
071 * @param clazz
072 * @return
073 */
074 @SuppressWarnings("unchecked")
075 public static <T> T getBean(Class<T> clazz) {
076 String[] beanNames = applicationContext.getBeanNamesForType(clazz);
077 // just return the first one
078 return (T) applicationContext.getBean(beanNames[0]);
079 }
080 }