1 16 17 package com.google.inject.spring; 18 19 import static com.google.inject.util.Objects.nonNull; 20 import com.google.inject.Provider; 21 import com.google.inject.Inject; 22 import com.google.inject.Binder; 23 import com.google.inject.name.Names; 24 import com.google.inject.spi.SourceProviders; 25 import com.google.inject.util.Objects; 26 import org.springframework.beans.factory.BeanFactory; 27 import org.springframework.beans.factory.ListableBeanFactory; 28 29 34 public class SpringIntegration { 35 36 static { 37 SourceProviders.skip(SpringIntegration.class); 38 } 39 40 private SpringIntegration() {} 41 42 52 public static <T> Provider<T> fromSpring(Class <T> type, String name) { 53 return new InjectableSpringProvider<T>(type, name); 54 } 55 56 64 public static void bindAll(Binder binder, ListableBeanFactory beanFactory) { 65 for (String name : beanFactory.getBeanDefinitionNames()) { 66 Class <?> type = beanFactory.getType(name); 67 bindBean(binder, beanFactory, name, type); 68 } 69 } 70 71 static <T> void bindBean(Binder binder, ListableBeanFactory beanFactory, 72 String name, Class <T> type) { 73 SpringProvider<T> provider 74 = SpringProvider.newInstance(type, name); 75 try { 76 provider.initialize(beanFactory); 77 } 78 catch (Exception e) { 79 binder.addError(e); 80 return; 81 } 82 83 binder.bind(type) 84 .annotatedWith(Names.named(name)) 85 .toProvider(provider); 86 } 87 88 static class SpringProvider<T> implements Provider<T> { 89 90 BeanFactory beanFactory; 91 boolean singleton; 92 final Class <T> type; 93 final String name; 94 95 public SpringProvider(Class <T> type, String name) { 96 this.type = nonNull(type, "type"); 97 this.name = nonNull(name, "name"); 98 } 99 100 static <T> SpringProvider<T> newInstance(Class <T> type, String name) { 101 return new SpringProvider<T>(type, name); 102 } 103 104 void initialize(BeanFactory beanFactory) { 105 this.beanFactory = beanFactory; 106 if (!beanFactory.isTypeMatch(name, type)) { 107 throw new ClassCastException ("Spring bean named '" + name 108 + "' does not implement " + type.getName() + "."); 109 } 110 singleton = beanFactory.isSingleton(name); 111 } 112 113 public T get() { 114 return singleton ? getSingleton() : type.cast(beanFactory.getBean(name)); 115 } 116 117 volatile T instance; 118 119 private T getSingleton() { 120 if (instance == null) { 121 instance = type.cast(beanFactory.getBean(name)); 122 } 123 return instance; 124 } 125 } 126 127 static class InjectableSpringProvider<T> extends SpringProvider<T> { 128 129 InjectableSpringProvider(Class <T> type, String name) { 130 super(type, name); 131 } 132 133 @Inject 134 @Override 135 void initialize(BeanFactory beanFactory) { 136 super.initialize(beanFactory); 137 } 138 } 139 } 140 | Popular Tags |