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.slf4j.Logger; 042 import org.slf4j.LoggerFactory; 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 065 */ 066 @XmlRootElement(name = "beanPostProcessor") 067 @XmlAccessorType(XmlAccessType.FIELD) 068 public class CamelBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware { 069 private static final transient Logger LOG = LoggerFactory.getLogger(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 injectFields(bean, beanName); 095 injectMethods(bean, beanName); 096 097 if (bean instanceof CamelContextAware && canSetCamelContext(bean, beanName)) { 098 CamelContextAware contextAware = (CamelContextAware)bean; 099 CamelContext context = getOrLookupCamelContext(); 100 if (context == null) { 101 LOG.warn("No CamelContext defined yet so cannot inject into bean: " + beanName); 102 } else { 103 contextAware.setCamelContext(context); 104 } 105 } 106 107 return bean; 108 } 109 110 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 111 if (LOG.isTraceEnabled()) { 112 LOG.trace("Camel bean processing after initialization for bean: " + beanName); 113 } 114 115 // some beans cannot be post processed at this given time, so we gotta check beforehand 116 if (!canPostProcessBean(bean, beanName)) { 117 return bean; 118 } 119 120 if (bean instanceof DefaultEndpoint) { 121 DefaultEndpoint defaultEndpoint = (DefaultEndpoint) bean; 122 defaultEndpoint.setEndpointUriIfNotSpecified(beanName); 123 } 124 125 return bean; 126 } 127 128 // Properties 129 // ------------------------------------------------------------------------- 130 131 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 132 this.applicationContext = applicationContext; 133 } 134 135 public CamelContext getCamelContext() { 136 return camelContext; 137 } 138 139 public void setCamelContext(CamelContext camelContext) { 140 this.camelContext = camelContext; 141 } 142 143 public String getCamelId() { 144 return camelId; 145 } 146 147 public void setCamelId(String camelId) { 148 this.camelId = camelId; 149 } 150 151 // Implementation methods 152 // ------------------------------------------------------------------------- 153 154 /** 155 * Can we post process the given bean? 156 * 157 * @param bean the bean 158 * @param beanName the bean name 159 * @return true to process it 160 */ 161 protected boolean canPostProcessBean(Object bean, String beanName) { 162 // the JMXAgent is a bit strange and causes Spring issues if we let it being 163 // post processed by this one. It does not need it anyway so we are good to go. 164 if (bean instanceof CamelJMXAgentDefinition) { 165 return false; 166 } 167 168 // all other beans can of course be processed 169 return true; 170 } 171 172 173 protected boolean canSetCamelContext(Object bean, String beanName) { 174 if (bean instanceof CamelContextAware) { 175 CamelContextAware camelContextAware = (CamelContextAware) bean; 176 CamelContext context = camelContextAware.getCamelContext(); 177 if (context != null) { 178 if (LOG.isTraceEnabled()) { 179 LOG.trace("CamelContext already set on bean with id [" + beanName + "]. Will keep existing CamelContext on bean."); 180 } 181 return false; 182 } 183 } 184 185 return true; 186 } 187 188 /** 189 * A strategy method to allow implementations to perform some custom JBI 190 * based injection of the POJO 191 * 192 * @param bean the bean to be injected 193 */ 194 protected void injectFields(final Object bean, final String beanName) { 195 ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { 196 public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { 197 EndpointInject endpointInject = field.getAnnotation(EndpointInject.class); 198 if (endpointInject != null && getPostProcessor().matchContext(endpointInject.context())) { 199 injectField(field, endpointInject.uri(), endpointInject.ref(), bean, beanName); 200 } 201 202 Produce produce = field.getAnnotation(Produce.class); 203 if (produce != null && getPostProcessor().matchContext(produce.context())) { 204 injectField(field, produce.uri(), produce.ref(), bean, beanName); 205 } 206 } 207 }); 208 } 209 210 protected void injectField(Field field, String endpointUri, String endpointRef, Object bean, String beanName) { 211 ReflectionUtils.setField(field, bean, getPostProcessor().getInjectionValue(field.getType(), endpointUri, endpointRef, field.getName(), bean, beanName)); 212 } 213 214 protected void injectMethods(final Object bean, final String beanName) { 215 ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() { 216 public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { 217 setterInjection(method, bean, beanName); 218 getPostProcessor().consumerInjection(method, bean, beanName); 219 } 220 }); 221 } 222 223 protected void setterInjection(Method method, Object bean, String beanName) { 224 EndpointInject endpointInject = method.getAnnotation(EndpointInject.class); 225 if (endpointInject != null && getPostProcessor().matchContext(endpointInject.context())) { 226 setterInjection(method, bean, beanName, endpointInject.uri(), endpointInject.ref()); 227 } 228 229 Produce produce = method.getAnnotation(Produce.class); 230 if (produce != null && getPostProcessor().matchContext(produce.context())) { 231 setterInjection(method, bean, beanName, produce.uri(), produce.ref()); 232 } 233 } 234 235 protected void setterInjection(Method method, Object bean, String beanName, String endpointUri, String endpointRef) { 236 Class<?>[] parameterTypes = method.getParameterTypes(); 237 if (parameterTypes != null) { 238 if (parameterTypes.length != 1) { 239 LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: " + method); 240 } else { 241 String propertyName = ObjectHelper.getPropertyName(method); 242 Object value = getPostProcessor().getInjectionValue(parameterTypes[0], endpointUri, endpointRef, propertyName, bean, beanName); 243 ObjectHelper.invokeMethod(method, bean, value); 244 } 245 } 246 } 247 248 protected CamelContext getOrLookupCamelContext() { 249 if (camelContext == null && applicationContext.containsBean(camelId)) { 250 camelContext = (CamelContext) applicationContext.getBean(camelId); 251 } 252 return camelContext; 253 } 254 255 public CamelPostProcessorHelper getPostProcessor() { 256 // lets lazily create the post processor 257 if (postProcessor == null) { 258 postProcessor = new CamelPostProcessorHelper() { 259 260 @Override 261 public CamelContext getCamelContext() { 262 // lets lazily lookup the camel context here 263 // as doing this will cause this context to be started immediately 264 // breaking the lifecycle ordering of different camel contexts 265 // so we only want to do this on demand 266 return getOrLookupCamelContext(); 267 } 268 269 @Override 270 protected RuntimeException createProxyInstantiationRuntimeException(Class<?> type, Endpoint endpoint, Exception e) { 271 return new BeanInstantiationException(type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e); 272 } 273 274 protected boolean isSingleton(Object bean, String beanName) { 275 // no application context has been injected which means the bean 276 // has not been enlisted in Spring application context 277 if (applicationContext == null || beanName == null) { 278 return super.isSingleton(bean, beanName); 279 } else { 280 return applicationContext.isSingleton(beanName); 281 } 282 } 283 284 protected void startService(Service service, Object bean, String beanName) throws Exception { 285 if (isSingleton(bean, beanName)) { 286 getCamelContext().addService(service); 287 } else { 288 // only start service and do not add it to CamelContext 289 ServiceHelper.startService(service); 290 if (prototypeBeans.add(beanName)) { 291 // do not spam the log with WARN so do this only once per bean name 292 LOG.warn("The bean with id [" + beanName + "] is prototype scoped and cannot stop the injected service when bean is destroyed: " 293 + service + ". You may want to stop the service manually from the bean."); 294 } 295 } 296 } 297 }; 298 } 299 return postProcessor; 300 } 301 302 }