View Javadoc
1   /**
2    * Copyright 2004-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.kpme.core.sys.context;
17  
18  import org.kuali.kpme.core.sys.constants.SpringBeans;
19  import org.springframework.beans.BeansException;
20  import org.springframework.context.ApplicationContext;
21  import org.springframework.context.ApplicationContextAware;
22  
23  /**
24   * helper class for spring beans stuff
25   * 
26   * Copied over from SpringContext.java from the LeaveManager Project
27   */
28  public class SpringContext implements ApplicationContextAware {
29  
30  	private static ApplicationContext applicationContext;
31  
32  	/**
33  	 * public constructor that throws exception if you try to instantiate it
34  	 * twice
35  	 * 
36  	 * @throws Exception
37  	 */
38  	public SpringContext() throws Exception {
39  		if (applicationContext != null)
40  			throw new Exception(
41  					"Cannot instantiate SpringContext twice. Use the static methods");
42  	}
43  
44  	/*
45  	 * (non-Javadoc)
46  	 * 
47  	 * @see
48  	 * org.springframework.context.ApplicationContextAware#setApplicationContext
49  	 * (org.springframework.context.ApplicationContext)
50  	 */
51  	@Override
52  	public void setApplicationContext(ApplicationContext applicationContext)
53  			throws BeansException {
54  		SpringContext.applicationContext = applicationContext;
55  	}
56  
57  	/**
58  	 * return a spring bean by its name
59  	 * 
60  	 * @param beanName
61  	 * @return
62  	 */
63  	public static Object getBean(SpringBeans bean) {
64  		return applicationContext.getBean(bean.toString());
65  	}
66  
67  	/**
68  	 * returns a spring bean by its class... this only works when the class name
69  	 * equals the spring bean name
70  	 * 
71  	 * @param clazz
72  	 * @return
73  	 */
74  	@SuppressWarnings("unchecked")
75  	public static <T> T getBean(Class<T> clazz) {
76  		String[] beanNames = applicationContext.getBeanNamesForType(clazz);
77  		// just return the first one
78  		return (T) applicationContext.getBean(beanNames[0]);
79  	}
80  }