1 /***
2 * Copyright (C) 2008 Jeremy Thomerson (jthomerson@users.sourceforge.net)
3 *
4 * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0
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
17 package net.sf.vcaperture.util.spring;
18
19 import net.sf.vcaperture.model.IApplicationContext;
20
21 import org.springframework.beans.BeansException;
22 import org.springframework.context.ApplicationContext;
23 import org.springframework.context.ApplicationContextAware;
24
25 /***
26 * The static factory which provides the context as necesary within the
27 * application.
28 *
29 * <p>
30 * TODO: This class assumes that only one context will ever be used within the
31 * container in which it is running. It could make use of a <tt>ThreadLocal</tt>
32 * (or similar) to provide for multiple contexts to be available.
33 * </p>
34 *
35 * <p>
36 * TODO: Not so much a factory as it is a locator. Perhaps should be renamed.
37 * </p>
38 *
39 * @author Jeremy Thomerson (jthomerson@users.sourceforge.net)
40 */
41 public class ApplicationContextFactory implements ApplicationContextAware {
42
43 private static final ApplicationContextFactory INSTANCE = new ApplicationContextFactory();
44
45 public static ApplicationContextFactory getFactory() {
46 return INSTANCE;
47 }
48
49 private IApplicationContext mWrapper;
50
51 public final IApplicationContext getContext() {
52 return mWrapper;
53 }
54
55 public final void setContext(ApplicationContext context) {
56 mWrapper = new AppContextWrapper(context);
57 }
58
59 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
60 getFactory().setContext(applicationContext);
61 }
62
63 private static class AppContextWrapper implements IApplicationContext {
64 private final ApplicationContext mContext;
65
66 private AppContextWrapper(ApplicationContext context) {
67 mContext = context;
68 }
69
70 @SuppressWarnings("unchecked")
71 public <T> T getBean(Class<T> clazz) {
72 return (T) mContext.getBean(clazz.getName());
73 }
74
75 public Object getBean(String name) {
76 return mContext.getBean(name);
77 }
78
79 public String getName() {
80 return (String) mContext.getBean("context-name");
81 }
82 }
83 }