001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.camel.spring; 018 019 import java.lang.reflect.Field; 020 import java.lang.reflect.Method; 021 import java.util.LinkedHashSet; 022 import java.util.Set; 023 024 import javax.xml.bind.annotation.XmlAccessType; 025 import javax.xml.bind.annotation.XmlAccessorType; 026 import javax.xml.bind.annotation.XmlRootElement; 027 import javax.xml.bind.annotation.XmlTransient; 028 029 import org.apache.camel.CamelContext; 030 import org.apache.camel.CamelContextAware; 031 import org.apache.camel.Endpoint; 032 import org.apache.camel.EndpointInject; 033 import org.apache.camel.Produce; 034 import org.apache.camel.Service; 035 import org.apache.camel.core.xml.CamelJMXAgentDefinition; 036 import org.apache.camel.impl.CamelPostProcessorHelper; 037 import org.apache.camel.impl.DefaultEndpoint; 038 import org.apache.camel.spring.util.ReflectionUtils; 039 import org.apache.camel.util.ObjectHelper; 040 import org.apache.camel.util.ServiceHelper; 041 import org.apache.commons.logging.Log; 042 import org.apache.commons.logging.LogFactory; 043 import org.springframework.beans.BeanInstantiationException; 044 import org.springframework.beans.BeansException; 045 import org.springframework.beans.factory.config.BeanPostProcessor; 046 import org.springframework.context.ApplicationContext; 047 import org.springframework.context.ApplicationContextAware; 048 049 /** 050 * A bean post processor which implements the <a href="http://camel.apache.org/bean-integration.html">Bean Integration</a> 051 * features in Camel. Features such as the <a href="http://camel.apache.org/bean-injection.html">Bean Injection</a> of objects like 052 * {@link Endpoint} and 053 * {@link org.apache.camel.ProducerTemplate} together with support for 054 * <a href="http://camel.apache.org/pojo-consuming.html">POJO Consuming</a> via the 055 * {@link org.apache.camel.Consume} annotation along with 056 * <a href="http://camel.apache.org/pojo-producing.html">POJO Producing</a> via the 057 * {@link org.apache.camel.Produce} annotation along with other annotations such as 058 * {@link org.apache.camel.RecipientList} for creating <a href="http://camel.apache.org/recipientlist-annotation.html">a Recipient List router via annotations</a>. 059 * <p> 060 * If you use the <camelContext> element in your <a href="http://camel.apache.org/spring.html">Spring XML</a> 061 * then one of these bean post processors is implicitly installed and configured for you. So you should never have to 062 * explicitly create or configure one of these instances. 063 * 064 * @version $Revision: 1044221 $ 065 */ 066 @XmlRootElement(name = "beanPostProcessor") 067 @XmlAccessorType(XmlAccessType.FIELD) 068 public class CamelBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware { 069 private static final transient Log LOG = LogFactory.getLog(CamelBeanPostProcessor.class); 070 @XmlTransient 071 Set<String> prototypeBeans = new LinkedHashSet<String>(); 072 @XmlTransient 073 private CamelContext camelContext; 074 @XmlTransient 075 private ApplicationContext applicationContext; 076 @XmlTransient 077 private CamelPostProcessorHelper postProcessor; 078 @XmlTransient 079 private String camelId; 080 081 public CamelBeanPostProcessor() { 082 } 083 084 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 085 if (LOG.isTraceEnabled()) { 086 LOG.trace("Camel bean processing before initialization for bean: " + beanName); 087 } 088 089 // some beans cannot be post processed at this given time, so we gotta check beforehand 090 if (!canPostProcessBean(bean, beanName)) { 091 return bean; 092 } 093 094 if (camelContext == null && applicationContext.containsBean(camelId)) { 095 setCamelContext((CamelContext) applicationContext.getBean(camelId)); 096 } 097 098 injectFields(bean, beanName); 099 injectMethods(bean, beanName); 100 101 if (bean instanceof CamelContextAware && canSetCamelContext(bean, beanName)) { 102 CamelContextAware contextAware = (CamelContextAware)bean; 103 if (camelContext == null) { 104 LOG.warn("No CamelContext defined yet so cannot inject into bean: " + beanName); 105 } else { 106 contextAware.setCamelContext(camelContext); 107 } 108 } 109 110 return bean; 111 } 112 113 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 114 if (LOG.isTraceEnabled()) { 115 LOG.trace("Camel bean processing after initialization for bean: " + beanName); 116 } 117 118 // some beans cannot be post processed at this given time, so we gotta check beforehand 119 if (!canPostProcessBean(bean, beanName)) { 120 return bean; 121 } 122 123 if (bean instanceof DefaultEndpoint) { 124 DefaultEndpoint defaultEndpoint = (DefaultEndpoint) bean; 125 defaultEndpoint.setEndpointUriIfNotSpecified(beanName); 126 } 127 128 return bean; 129 } 130 131 // Properties 132 // ------------------------------------------------------------------------- 133 134 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 135 this.applicationContext = applicationContext; 136 } 137 138 public CamelContext getCamelContext() { 139 return camelContext; 140 } 141 142 public void setCamelContext(CamelContext camelContext) { 143 this.camelContext = camelContext; 144 postProcessor = new CamelPostProcessorHelper(camelContext) { 145 @Override 146 protected RuntimeException createProxyInstantiationRuntimeException(Class<?> type, Endpoint endpoint, Exception e) { 147 return new BeanInstantiationException(type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e); 148 } 149 150 protected boolean isSingleton(Object bean, String beanName) { 151 // no application context has been injected which means the bean 152 // has not been enlisted in Spring application context 153 if (applicationContext == null || beanName == null) { 154 return super.isSingleton(bean, beanName); 155 } else { 156 return applicationContext.isSingleton(beanName); 157 } 158 } 159 160 protected void startService(Service service, Object bean, String beanName) throws Exception { 161 if (isSingleton(bean, beanName)) { 162 getCamelContext().addService(service); 163 } else { 164 // only start service and do not add it to CamelContext 165 ServiceHelper.startService(service); 166 if (prototypeBeans.add(beanName)) { 167 // do not spam the log with WARN so do this only once per bean name 168 LOG.warn("The bean with id [" + beanName + "] is prototype scoped and cannot stop the injected service when bean is destroyed: " 169 + service + ". You may want to stop the service manually from the bean."); 170 } 171 } 172 } 173 }; 174 } 175 176 public String getCamelId() { 177 return camelId; 178 } 179 180 public void setCamelId(String camelId) { 181 this.camelId = camelId; 182 } 183 184 // Implementation methods 185 // ------------------------------------------------------------------------- 186 187 /** 188 * Can we post process the given bean? 189 * 190 * @param bean the bean 191 * @param beanName the bean name 192 * @return true to process it 193 */ 194 protected boolean canPostProcessBean(Object bean, String beanName) { 195 // the JMXAgent is a bit strange and causes Spring issues if we let it being 196 // post processed by this one. It does not need it anyway so we are good to go. 197 if (bean instanceof CamelJMXAgentDefinition) { 198 return false; 199 } 200 201 // all other beans can of course be processed 202 return true; 203 } 204 205 206 protected boolean canSetCamelContext(Object bean, String beanName) { 207 if (bean instanceof CamelContextAware) { 208 CamelContextAware camelContextAware = (CamelContextAware) bean; 209 CamelContext context = camelContextAware.getCamelContext(); 210 if (context != null) { 211 if (LOG.isTraceEnabled()) { 212 LOG.trace("CamelContext already set on bean with id [" + beanName + "]. Will keep existing CamelContext on bean."); 213 } 214 return false; 215 } 216 } 217 218 return true; 219 } 220 221 /** 222 * A strategy method to allow implementations to perform some custom JBI 223 * based injection of the POJO 224 * 225 * @param bean the bean to be injected 226 */ 227 protected void injectFields(final Object bean, final String beanName) { 228 ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { 229 public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { 230 EndpointInject endpointInject = field.getAnnotation(EndpointInject.class); 231 if (endpointInject != null && postProcessor.matchContext(endpointInject.context())) { 232 injectField(field, endpointInject.uri(), endpointInject.ref(), bean, beanName); 233 } 234 235 Produce produce = field.getAnnotation(Produce.class); 236 if (produce != null && postProcessor.matchContext(produce.context())) { 237 injectField(field, produce.uri(), produce.ref(), bean, beanName); 238 } 239 } 240 }); 241 } 242 243 protected void injectField(Field field, String endpointUri, String endpointRef, Object bean, String beanName) { 244 ReflectionUtils.setField(field, bean, getPostProcessor().getInjectionValue(field.getType(), endpointUri, endpointRef, field.getName(), bean, beanName)); 245 } 246 247 protected void injectMethods(final Object bean, final String beanName) { 248 ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() { 249 public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { 250 setterInjection(method, bean, beanName); 251 getPostProcessor().consumerInjection(method, bean, beanName); 252 } 253 }); 254 } 255 256 protected void setterInjection(Method method, Object bean, String beanName) { 257 EndpointInject endpointInject = method.getAnnotation(EndpointInject.class); 258 if (endpointInject != null && postProcessor.matchContext(endpointInject.context())) { 259 setterInjection(method, bean, beanName, endpointInject.uri(), endpointInject.ref()); 260 } 261 262 Produce produce = method.getAnnotation(Produce.class); 263 if (produce != null && postProcessor.matchContext(produce.context())) { 264 setterInjection(method, bean, beanName, produce.uri(), produce.ref()); 265 } 266 } 267 268 protected void setterInjection(Method method, Object bean, String beanName, String endpointUri, String endpointRef) { 269 Class<?>[] parameterTypes = method.getParameterTypes(); 270 if (parameterTypes != null) { 271 if (parameterTypes.length != 1) { 272 LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: " + method); 273 } else { 274 String propertyName = ObjectHelper.getPropertyName(method); 275 Object value = getPostProcessor().getInjectionValue(parameterTypes[0], endpointUri, endpointRef, propertyName, bean, beanName); 276 ObjectHelper.invokeMethod(method, bean, value); 277 } 278 } 279 } 280 281 public CamelPostProcessorHelper getPostProcessor() { 282 ObjectHelper.notNull(postProcessor, "postProcessor"); 283 return postProcessor; 284 } 285 286 }