01: package com.technoetic.xplanner.util;
02:
03: import org.springframework.beans.factory.BeanFactory;
04: import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
05: import org.springframework.beans.factory.config.ConfigurableBeanFactory;
06: import org.springframework.beans.factory.support.DefaultListableBeanFactory;
07: import org.springframework.beans.factory.support.RootBeanDefinition;
08: import org.springframework.beans.factory.xml.XmlBeanFactory;
09: import org.springframework.beans.BeansException;
10: import org.springframework.core.io.ClassPathResource;
11: import org.apache.log4j.Logger;
12:
13: public class MainBeanFactory {
14: public static BeanFactory factory = createDefaultFactory();
15: public static final String DEFAULT_BEANS_REGISTRY_PATH = "/spring-beans.xml";
16: protected static final Logger LOG = LogUtil.getLogger();
17:
18: private static XmlBeanFactory createDefaultFactory() {
19: try {
20: return new XmlBeanFactory(new ClassPathResource(
21: DEFAULT_BEANS_REGISTRY_PATH));
22: } catch (Throwable e) {
23: e.printStackTrace();
24: return null;
25: }
26: }
27:
28: public static void reset() {
29: factory = createDefaultFactory();
30: }
31:
32: public static Object getBean(Class type) {
33: return getBean(type.getName());
34: }
35:
36: public static Object getBean(Class type, boolean logFailures) {
37: return getBean(type.getName(), logFailures);
38: }
39:
40: public static Object getBean(String name) {
41: return factory.getBean(name);
42: }
43:
44: public static Object getBean(String name, boolean logFailures) {
45: try {
46: return getBean(name);
47: } catch (BeansException e) {
48: if (logFailures)
49: LOG.error(e.getMessage(), e);
50: throw e;
51: }
52: }
53:
54: public static void setBean(Class type, Object singleton) {
55: ((ConfigurableBeanFactory) factory).registerSingleton(type
56: .getName(), singleton);
57: }
58:
59: public static void setBean(String name, Object singleton) {
60: ((ConfigurableBeanFactory) factory).registerSingleton(name,
61: singleton);
62: }
63:
64: public static void initBeanProperties(Object bean) {
65: ((AutowireCapableBeanFactory) factory)
66: .autowireBeanProperties(bean,
67: AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
68: true);
69: }
70:
71: public static void registerBeanDefinition(Class typeName,
72: Class beanClass) {
73: ((DefaultListableBeanFactory) factory).registerBeanDefinition(
74: typeName.getName(), new RootBeanDefinition(beanClass,
75: RootBeanDefinition.AUTOWIRE_AUTODETECT));
76: }
77: }
|