View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.orchestra.conversation.spring;
21  
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import org.aopalliance.aop.Advice;
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.myfaces.orchestra.conversation.Conversation;
29  import org.apache.myfaces.orchestra.conversation.ConversationAware;
30  import org.apache.myfaces.orchestra.conversation.ConversationBindingEvent;
31  import org.apache.myfaces.orchestra.conversation.ConversationBindingListener;
32  import org.apache.myfaces.orchestra.conversation.ConversationContext;
33  import org.apache.myfaces.orchestra.conversation.ConversationFactory;
34  import org.apache.myfaces.orchestra.conversation.ConversationManager;
35  import org.apache.myfaces.orchestra.conversation.CurrentConversationAdvice;
36  import org.apache.myfaces.orchestra.frameworkAdapter.FrameworkAdapter;
37  import org.springframework.aop.Advisor;
38  import org.springframework.aop.SpringProxy;
39  import org.springframework.aop.framework.ProxyFactory;
40  import org.springframework.aop.framework.autoproxy.AutoProxyUtils;
41  import org.springframework.aop.scope.ScopedProxyFactoryBean;
42  import org.springframework.beans.BeansException;
43  import org.springframework.beans.factory.BeanFactory;
44  import org.springframework.beans.factory.BeanFactoryAware;
45  import org.springframework.beans.factory.ObjectFactory;
46  import org.springframework.beans.factory.config.BeanDefinition;
47  import org.springframework.beans.factory.config.BeanPostProcessor;
48  import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
49  import org.springframework.beans.factory.config.Scope;
50  import org.springframework.context.ApplicationContext;
51  import org.springframework.context.ApplicationContextAware;
52  import org.springframework.context.ConfigurableApplicationContext;
53  
54  /**
55   * Abstract basis class for all the Orchestra scopes.
56   * <p>
57   * A scope object has two quite different roles:
58   * <ol>
59   * <li>It handles the lookup of beans in a scope, and creates them if needed</li>
60   * <li>It handles the creation of Conversation objects, using the spring properties
61   * configured on the scope object.</li>
62   * </ol>
63   * <p>
64   * This base class handles item 1 above, and leaves item 2 to a subclass. The
65   * declaration of interface ConversationFactory needs to be on this class, however,
66   * as the createBean method needs to invoke it.
67   */
68  public abstract class AbstractSpringOrchestraScope implements
69      ConversationFactory, // Orchestra interfaces
70      Scope, BeanFactoryAware, ApplicationContextAware // Spring interfaces
71  {
72      private static final Advice[] NO_ADVICES = new Advice[0];
73      private static final String POST_PROCESSOR_BEAN_NAME =
74          AbstractSpringOrchestraScope.class.getName() + "_BeanPostProcessor";
75  
76      private final Log log = LogFactory.getLog(AbstractSpringOrchestraScope.class);
77  
78      private ConfigurableApplicationContext applicationContext;
79      private Advice[] advices;
80      private boolean autoProxy = true;
81  
82      public AbstractSpringOrchestraScope()
83      {
84      }
85  
86      /**
87       * The advices (interceptors) which will be applied to the conversation scoped bean.
88       * These are applied whenever a method is invoked on the bean [1].
89       * <p>
90       * An application's spring configuration uses this method to control what advices are
91       * applied to beans generated from this scope. One commonly applied advice is the
92       * Orchestra persistence interceptor, which ensures that whenever a method on a
93       * conversation-scoped bean is invoked the "global persistence context" is set
94       * to the context for the conversation that bean is in.
95       * <p>
96       * Note [1]: the advices are only applied when the bean is invoked via its proxy. If
97       * invoked via the "this" pointer of the object the interceptors will not run. This
98       * is generally a good thing, as they are not wanted when a method on the bean invokes
99       * another method on the same bean. However it is bad if the bean passes "this" as a
100      * parameter to some other object that makes a callback on it at some later time. In
101      * that case, the bean must take care to pass its proxy to the remote object, not
102      * itself. See method ConversationUtils.getCurrentBean().
103      */
104     public void setAdvices(Advice[] advices)
105     {
106         this.advices = advices;
107     }
108 
109     /**
110      * @since 1.1
111      */
112     protected Advice[] getAdvices()
113     {
114         return advices;
115     }
116 
117     /**
118      * Configuration for a scope object to control whether "scoped proxy" objects are
119      * automatically wrapped around each conversation bean.
120      * <p>
121      * Automatically applying scope proxies solves a lot of tricky problems with "stale"
122      * beans, and should generally be used. However it does require CGLIB to be present
123      * in the classpath. It also can impact performance in some cases. Where this is a
124      * problem, this flag can turn autoproxying off. Note that the standard spring
125      * aop:scoped-proxy bean can then be used on individual beans to re-enable
126      * proxying for specific beans if desired.
127      * <p>
128      * This defaults to true.
129      *
130      * @since 1.1
131      */
132     public void setAutoProxy(boolean state)
133     {
134         autoProxy = state;
135     }
136 
137     /**
138      * Return the conversation context id.
139      * <p>
140      * Note: This conversationId is something spring requires. It has nothing to do with the Orchestra
141      * conversation id.
142      * <p>
143      * TODO: what does Spring use this for????
144      */
145     public String getConversationId()
146     {
147         ConversationManager manager = ConversationManager.getInstance();
148         ConversationContext ctx = manager.getCurrentConversationContext();
149         if (ctx != null)
150         {
151             return Long.toString(ctx.getId(), 10);
152         }
153 
154         return null;
155     }
156 
157     /**
158      * This is invoked by Spring whenever someone calls getBean(name) on a bean-factory
159      * and the bean-definition for that bean has a scope attribute that maps to an
160      * instance of this class.
161      * <p>
162      * In the normal case, this method returns an internally-created proxy object
163      * that fetches the "real" bean every time a method is invoked on the proxy
164      * (see method getRealBean). This does obviously have some performance impact.
165      * However it is necessary when beans from one conversation are referencing beans
166      * from another conversation as the conversation lifetimes are not the same;
167      * without this proxying there are many cases where "stale" references end up
168      * being used. Most references to conversation-scoped objects are made via EL
169      * expressions, and in this case the performance impact is not significant
170      * relative to the overhead of EL. Note that there is one case where this
171      * proxying is not "transparent" to user code: if a proxied object passes a
172      * "this" pointer to a longer-lived object that retains that pointer then
173      * that reference can be "stale", as it points directly to an instance rather
174      * than to the proxy.
175      * <p>
176      * When the Spring aop:scoped-proxy feature is applied to conversation-scoped
177      * beans, then this functionality is disabled as aop:scoped-proxy has a very
178      * similar effect. Therefore, when this method detects that it has been invoked
179      * by a proxy object generated by aop:scoped-proxy then it returns the real
180      * object (see getRealBean) rather than another proxy. Using aop:scoped-proxy
181      * is somewhat less efficient than Orchestra's customised proxying.
182      * <p>
183      * And when the orchestra proxy needs to access the real object, it won't
184      * call this method; instead, getRealBean is called directly. See class
185      * ScopedBeanTargetSource.
186      */
187     public Object get(String name, ObjectFactory objectFactory)
188     {
189         if (log.isDebugEnabled())
190         {
191             log.debug("Method get called for bean " + name);
192         }
193 
194         if (_SpringUtils.isModifiedBeanName(name))
195         {
196             // Backwards compatibility with aop:scoped-proxy tag.
197             //
198             // The user must have included an aop:scoped-proxy within the bean definition,
199             // and here the proxy is firing to try to get the underlying bean. In this
200             // case, return a non-proxied instance of the referenced bean.
201             try
202             {
203                 String originalBeanName = _SpringUtils.getOriginalBeanName(name);
204                 String conversationName = getConversationNameForBean(name);
205                 return getRealBean(conversationName, originalBeanName, objectFactory);
206             }
207             catch(RuntimeException e)
208             {
209                 log.error("Exception while accessing bean '" + name + "'");
210                 throw e;
211             }
212         }
213         else if (!autoProxy)
214         {
215             String conversationName = getConversationNameForBean(name);
216             return getRealBean(conversationName, name, objectFactory);
217         }
218         else
219         {
220             // A call has been made by the user to the Spring getBean method
221             // (directly, or via an EL expression). Or the bean is being fetched
222             // as part of spring injection into another object.
223             //
224             // In all these cases, just return a proxy.
225             return getProxy(name, objectFactory);
226         }
227     }
228 
229     /**
230      * Return a CGLIB-generated proxy class for the beanclass that is
231      * specified by the provided beanName.
232      * <p>
233      * When any method is invoked on this proxy, it invokes method
234      * getRealBean on this same instance in order to locate a proper
235      * instance, then forwards the method call to it.
236      * <p>
237      * There is a separate proxy instance per beandef (shared across all
238      * instances of that bean). This instance is created when first needed,
239      * and cached for reuse.
240      *
241      * @since 1.1
242      */
243     protected Object getProxy(String beanName, ObjectFactory objectFactory)
244     {
245         if (log.isDebugEnabled())
246         {
247             log.debug("getProxy called for bean " + beanName);
248         }
249 
250         BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(beanName);
251         String conversationName = getConversationNameForBean(beanName);
252 
253         // deal with proxies required for multiple conversations.
254         // This is required to make the viewController scope work where proxies are
255         // required for each conversation a bean has been requested.
256         Map proxies = (Map) beanDefinition.getAttribute(ScopedBeanTargetSource.class.getName());
257         if (proxies == null)
258         {
259             proxies = new HashMap();
260             beanDefinition.setAttribute(ScopedBeanTargetSource.class.getName(), proxies);
261         }
262 
263         Object proxy = proxies.get(conversationName);
264         if (proxy == null)
265         {
266             if (log.isDebugEnabled())
267             {
268                 log.debug("getProxy: creating proxy for " + beanName);
269             }
270             BeanFactory beanFactory = applicationContext.getBeanFactory();
271             proxy = _SpringUtils.newProxy(this, conversationName, beanName, objectFactory, beanFactory);
272             proxies.put(conversationName, proxy);
273         }
274 
275         // Register the proxy in req scope. The first lookup of a variable using an EL expression during a
276         // request will therefore take the "long" path through JSF's VariableResolver and Spring to get here.
277         // But later lookups of this variable in the same request find the proxy directly in the request scope.
278         // The proxy could potentially be placed in the session or app scope, as there is just one instance
279         // for this spring context, and there is normally only one spring context for a webapp. However
280         // using the request scope is almost as efficient and seems safer.
281         //
282         // Note that the framework adapter might not be initialised during the Spring context initialisation
283         // phase (ie instantiation of singletons during startup), so just skip registration in those cases.
284         FrameworkAdapter fa = FrameworkAdapter.getCurrentInstance();
285         if (fa != null)
286         {
287             fa.setRequestAttribute(beanName, proxy);
288         }
289 
290 
291         return proxy;
292     }
293 
294     /**
295      * Get a real bean instance (not a scoped-proxy).
296      * <p>
297      * The appropriate Conversation is retrieved; if it does not yet exist then
298      * it is created and started. The conversation name is either specified on the
299      * bean-definition via a custom attribute, or defaults to the bean name.
300      * <p>
301      * Then if the bean already exists in the Conversation it is returned. Otherwise
302      * a new instance is created, stored into the Conversation and returned.
303      * <p>
304      * When a bean is created, a proxy is actually created for it which has one or
305      * more AOP "advices" (ie method interceptors). The CurrentConversationAdvice class
306      * is always attached. Note that if the bean definition contains the aop:proxy
307      * tag (and most do) then the bean that spring creates is already a proxy, ie
308      * what is returned is a proxy of a proxy.
309      *
310      * @param conversationName
311      * @param beanName is the key within the conversation of the bean we are interested in.
312      *
313      * @since 1.1
314      */
315     protected Object getRealBean(String conversationName, String beanName, ObjectFactory objectFactory)
316     {
317         if (log.isDebugEnabled())
318         {
319             log.debug("getRealBean called for bean " + beanName);
320         }
321         ConversationManager manager = ConversationManager.getInstance();
322         Conversation conversation;
323 
324         // check if we have a conversation
325         synchronized(manager)
326         {
327             conversation = manager.getConversation(conversationName);
328             if (conversation == null)
329             {
330                 // Start the conversation. This eventually results in a
331                 // callback to the createConversation method on this class.
332                 conversation = manager.startConversation(conversationName, this);
333             }
334             else
335             {
336                 // sanity check: verify that two beans with the different scopes
337                 // do not declare the same conversationName.
338                 assertSameScope(beanName, conversation);
339             }
340         }
341 
342         // get the conversation
343         notifyAccessConversation(conversation);
344         synchronized(conversation)
345         {
346             if (!conversation.hasAttribute(beanName))
347             {
348                 Object value;
349 
350                 // Set the magic property that forces all proxies of this bean to be CGLIB proxies.
351                 // It doesn't matter if we do this multiple times..
352                 BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(beanName);
353                 beanDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
354 
355                 try
356                 {
357                     // Create the new bean. Note that this will run the
358                     // OrchestraAdvisorBeanPostProcessor processor, which
359                     // will cause the returned object to actually be a proxy
360                     // with the CurrentConversationAdvice (at least) attached to it.
361                     value = objectFactory.getObject();
362                 }
363                 catch(org.springframework.aop.framework.AopConfigException e)
364                 {
365                     throw new IllegalStateException(
366                         "Unable to create Orchestra proxy"
367                             + " for bean " + beanName, e);
368                 }
369 
370                 conversation.setAttribute(beanName, value);
371 
372                 if (value instanceof ConversationAware)
373                 {
374                     ((ConversationAware) value).setConversation(conversation);
375                 }
376             }
377         }
378 
379         // get the bean
380         return conversation.getAttribute(beanName);
381     }
382 
383     /**
384      * Verify that the specified conversation was created by this scope object.
385      *
386      * @param beanName is just used when generating an error message on failure.
387      * @param conversation is the conversation to validate.
388      */
389     protected void assertSameScope(String beanName, Conversation conversation)
390     {
391         // Check that the conversation's factory is this one.
392         //
393         // This handles the case where two different beans declare themselves
394         // as belonging to the same named conversation but with different scope
395         // objects. Allowing that would be nasty, as the conversation
396         // properties (eg lifetime of access or manual) would depend upon which
397         // bean got created first; some other ConversationFactory would have
398         // created the conversation using its configured properties then
399         // we are now adding to that conversation a bean that really wants
400         // the conversation properties defined on this ConversationFactory.
401         //
402         // Ideally the conversation properties would be defined using
403         // the conversation name, not the scope name; this problem would
404         // then not exist. However that would lead to some fairly clumsy
405         // configuration, particularly where lots of beans without explicit
406         // conversationName attributes are used.
407 
408         if (conversation.getFactory() != this)
409         {
410             throw new IllegalArgumentException(
411                 "Inconsistent scope and conversation name detected for bean "
412                     + beanName);
413         }
414     }
415 
416     protected void notifyAccessConversation(Conversation conversation)
417     {
418     }
419 
420     /**
421      * Invoked by Spring to notify this object of the BeanFactory it is associated with.
422      * <p>
423      * This method is redundant as we also have setApplicationContext. However as this
424      * method (and the BeanFactoryAware interface on this class) were present in release
425      * 1.0 this needs to be kept for backwards compatibility.
426      */
427     public void setBeanFactory(BeanFactory beanFactory) throws BeansException
428     {
429     }
430 
431     /**
432      * Register any BeanPostProcessors that are needed by this scope.
433      * <p>
434      * This is an alternative to requiring users to also add an orchestra BeanPostProcessor element
435      * to their xml configuration file manually.
436      * <p>
437      * When a bean <i>instance</i> is created by Spring, it always runs every single BeanPostProcessor
438      * that has been registered with it.
439      *
440      * @since 1.1
441      */
442     public void defineBeanPostProcessors(ConfigurableListableBeanFactory cbf) throws BeansException
443     {
444         if (!cbf.containsSingleton(POST_PROCESSOR_BEAN_NAME))
445         {
446             BeanPostProcessor processor = new OrchestraAdvisorBeanPostProcessor(applicationContext);
447 
448             // Adding the bean to the singletons set causes it to be picked up by the standard
449             // AbstractApplicationContext.RegisterBeanPostProcessors method; that calls
450             // getBeanNamesForType(BeanPostProcessor.class, ...) which finds stuff in the
451             // singleton map even when there is no actual BeanDefinition for it.
452             //
453             // We cannot call cbf.addBeanPostProcessor even if we want to, as the singleton
454             // registration will be added again, making the processor run twice on each bean.
455             // And we need the singleton registration in order to avoid registering this once
456             // for each scope object defined in spring.
457             cbf.registerSingleton(POST_PROCESSOR_BEAN_NAME, processor);
458         }
459     }
460 
461     /**
462      * Get the conversation for the given beanName.
463      * Returns null if the conversation does not exist.
464      */
465     protected Conversation getConversationForBean(String beanDefName)
466     {
467         ConversationManager manager = ConversationManager.getInstance();
468         String conversationName = getConversationNameForBean(beanDefName);
469         Conversation conversation = manager.getConversation(conversationName);
470         return conversation;
471     }
472 
473     /**
474      * Get the conversation-name for bean instances created using the specified
475      * bean definition.
476      */
477     public String getConversationNameForBean(String beanName)
478     {
479         if (applicationContext == null)
480         {
481             throw new IllegalStateException("Null application context");
482         }
483 
484         // Look up the definition with the specified name.
485         BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(beanName);
486 
487         if (ScopedProxyFactoryBean.class.getName().equals(beanDefinition.getBeanClassName()))
488         {
489             // Handle unusual case.
490             //
491             // The user bean must have been defined like this:
492             //  <bean name="foo" class="example.Foo">
493             //    <....>
494             //    <aop:scopedProxy/>
495             //  </bean>
496             // In this case, Spring's ScopedProxyUtils class creates two BeanDefinition objects, one
497             // with name "foo" that creates a proxy object, and one with name "scopedTarget.foo"
498             // that actually defines the bean of type example.Foo.
499             //
500             // So what we do here is find the renamed bean definition and look there.
501             //
502             // This case does not occur when this method is invoked from within this class; the
503             // spring scope-related callbacks always deal with the beandef that is scoped to
504             // this scope - which is the original (though renamed) beandef.
505             beanName = _SpringUtils.getModifiedBeanName(beanName);
506             beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(beanName); // NON-NLS
507         }
508 
509         String convName = getExplicitConversationName(beanDefinition);
510         if (convName == null)
511         {
512             // The beanname might have been of form "scopedTarget.foo" (esp from registerDestructionCallback).
513             // But in this case, the conversation name will just be "foo", so strip the prefix off.
514             //
515             // Note that this does happen quite often for calls from within this class when aop:scoped-proxy
516             // is being used (which is not recommended but is supported).
517             convName = _SpringUtils.getOriginalBeanName(beanName);
518         }
519         return convName;
520     }
521 
522     /**
523      * Return the explicit conversation name for this bean definition, or null if there is none.
524      * <p>
525      * This is a separate method so that subclasses can determine conversation names via alternate methods.
526      * In particular, a subclass may want to look for an annotation on the class specified by the definition.
527      *
528      * @since 1.1
529      */
530     protected String getExplicitConversationName(BeanDefinition beanDef)
531     {
532         String attr = (String) beanDef.getAttribute(
533                 BeanDefinitionConversationNameAttrDecorator.CONVERSATION_NAME_ATTRIBUTE);
534         return attr;
535     }
536 
537     /**
538      * Strip off any Spring namespace (eg scopedTarget).
539      * <p>
540      * This method will simply strip off anything before the first dot.
541      *
542      * @deprecated Should not be necessary in user code.
543      */
544     protected String buildBeanName(String name)
545     {
546         if (name == null)
547         {
548             return null;
549         }
550 
551         int pos = name.indexOf('.');
552         if (pos < 0)
553         {
554             return name;
555         }
556 
557         return name.substring(pos + 1);
558     }
559 
560     public Object remove(String name)
561     {
562         throw new UnsupportedOperationException();
563     }
564 
565     /**
566      * Add the given runnable wrapped within an
567      * {@link org.apache.myfaces.orchestra.conversation.ConversationBindingListener} to
568      * the conversation map.
569      * <p>
570      * This ensures it will be called during conversation destroy.
571      * <p>
572      * Spring calls this method whenever a bean in this scope is created, if that bean
573      * has a "destroy method". Note however that it appears that it can also call it even
574      * for beans that do not have a destroy method when there is a "destruction aware"
575      * BeanPostProcessor attached to the context (spring version 2.5 at least).
576      * <p>
577      * When an aop:scoped-proxy has been used inside the bean, then the "new" definition
578      * does not have any scope attribute, so orchestra is not invoked for it. However
579      * the "renamed" bean does, and so this is called.
580      */
581     public void registerDestructionCallback(String name, final Runnable runnable)
582     {
583         if (log.isDebugEnabled())
584         {
585             log.debug("registerDestructionCallback for [" + name + "]");
586         }
587 
588         Conversation conversation = getConversationForBean(name);
589         if (conversation == null)
590         {
591             // This should never happen because this should only be called after the bean
592             // instance has been created via scope.getBean, which always creates the
593             // conversation for the bean.
594             throw new IllegalStateException("No conversation for bean [" + name + "]");
595         }
596         if (runnable == null)
597         {
598             throw new IllegalStateException("No runnable object for bean [" + name + "]");
599         }
600 
601         // Add an object to the conversation as a bean so that when the conversation is removed
602         // its valueUnbound method will be called. However we never need to retrieve this object
603         // from the context by name, so use a totally unique name as the bean key.
604         conversation.setAttribute(
605             runnable.getClass().getName() + "@" + System.identityHashCode(runnable),
606             new ConversationBindingListener()
607             {
608                 public void valueBound(ConversationBindingEvent event)
609                 {
610                 }
611 
612                 public void valueUnbound(ConversationBindingEvent event)
613                 {
614                     runnable.run();
615                 }
616             }
617         );
618     }
619 
620     /**
621      * Get an ApplicationContext injected by Spring. See ApplicationContextAware interface.
622      */
623     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
624     {
625         if (!(applicationContext instanceof ConfigurableApplicationContext))
626         {
627             throw new IllegalArgumentException("a ConfigurableApplicationContext is required");
628         }
629 
630         this.applicationContext = (ConfigurableApplicationContext) applicationContext;
631         defineBeanPostProcessors(this.applicationContext.getBeanFactory());
632     }
633 
634     /**
635      * @since 1.2
636      */
637     protected ConfigurableApplicationContext getApplicationContext()
638     {
639         return applicationContext;
640     }
641 
642     /**
643      * Return the Advisors that should be applied to beans associated with this scope object.
644      * <p>
645      * Note that logically Advisors are associated with a Conversation. It is an implementation
646      * artifact of the Spring implementation of Orchestra that we use a spring Scope object to
647      * hold the advices; theoretically with other dependency-injection frameworks we could
648      * configure things differently. 
649      */
650     Advisor[] getAdvisors(Conversation conversation, String beanName)
651     {
652         Advice[] advices = this.getAdvices();
653         if ((advices == null) || (advices.length == 0))
654         {
655             advices = NO_ADVICES;
656         }
657 
658         // wrap every Advice in an Advisor instance that returns it in all cases
659         int len = advices.length + 1;
660         Advisor[] advisors = new Advisor[len];
661 
662         // always add the standard CurrentConversationAdvice, and do it FIRST, so it runs first
663         Advice currConvAdvice = new CurrentConversationAdvice(conversation, beanName);
664         advisors[0] = new SimpleAdvisor(currConvAdvice);
665         for(int i=0; i<advices.length; ++i) 
666         {
667             advisors[i+1] = new SimpleAdvisor(advices[i]);
668         }
669 
670         return advisors;
671     }
672 
673     /**
674      * Return a proxy object that "enters" the specified conversation before forwarding the
675      * method call on to the specified instance.
676      * <p>
677      * Entering the conversation means running all the Advices associated with the conversation.
678      * The specified conversation object is assumed to use this Scope object.
679      */
680     Object createProxyFor(Conversation conversation, Object instance)
681     {
682         if (instance instanceof SpringProxy)
683         {
684             // This is already a proxy, so don't wrap it again. Doing this check means that
685             // user code can safely write things like
686             //    return ConversationUtils.bindToCurrent(this)
687             // without worrying about whether "this" is a spring bean marked as conversation-scoped
688             // or not. Requiring beans to know about the configuration setup is bad practice.
689             //
690             // Ideally we would check here that this instance is indeed a proxy for the
691             // specified conversation and throw an exception. However that is just a
692             // nice-to-have.
693             return instance;
694         }
695         
696         // The currentConversationAdvice constructor requires a beanName parameter. As the
697         // instance we are wrapping here is usually not defined in the dependency-injection
698         // framework configuration at all, we have to invent a dummy name here.
699         //
700         // The beanName affects ConversationUtils methods getCurrentBean and invalidateAndRestartCurrent.
701         // Neither should ever be called by beans artificially wrapped in a proxy like this, so any old
702         // "bean name" will do. Including the class-name of the bean we wrap seems helpful here..
703         String beanName = "dummy$" + instance.getClass().getName();
704 
705         ProxyFactory proxyFactory = new ProxyFactory(instance);
706         proxyFactory.setProxyTargetClass(true);
707         Advisor[] advisors = getAdvisors(conversation, beanName);
708         for(int i=0; i<advisors.length; ++i)
709         {
710             proxyFactory.addAdvisor(advisors[i]);
711         }
712 
713         proxyFactory.addInterface(SpringProxy.class);
714         return proxyFactory.getProxy(instance.getClass().getClassLoader());
715     }
716 }