View Javadoc

1   package com.atlassian.plugin.spring;
2   
3   import com.atlassian.plugin.osgi.hostcomponents.ComponentRegistrar;
4   import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider;
5   import org.springframework.beans.BeansException;
6   import org.springframework.beans.factory.BeanFactory;
7   import org.springframework.beans.factory.BeanFactoryAware;
8   import org.springframework.beans.factory.BeanIsAbstractException;
9   import org.springframework.beans.factory.ListableBeanFactory;
10  import org.springframework.stereotype.Component;
11  import org.springframework.aop.SpringProxy;
12  import org.springframework.aop.support.AopUtils;
13  import org.springframework.core.annotation.AnnotationUtils;
14  
15  import java.lang.annotation.Annotation;
16  import java.lang.reflect.Proxy;
17  
18  /**
19   * Host component provider that scans the bean factory for all beans that implement @AvailableToPlugins and registers
20   * them.
21   */
22  @Component("hostComponentProvider")
23  public class SpringHostComponentProvider implements HostComponentProvider, BeanFactoryAware
24  {
25      private BeanFactory beanFactory = null;
26  
27      public void setBeanFactory(BeanFactory beanFactory) throws BeansException
28      {
29          this.beanFactory = beanFactory;
30      }
31  
32      public void provide(ComponentRegistrar registrar)
33      {
34          ListableBeanFactory lbf;
35          if (beanFactory instanceof ListableBeanFactory) {
36              lbf = (ListableBeanFactory) beanFactory;
37              String[] names = lbf.getBeanDefinitionNames();
38  
39              for (String name : names)
40              {
41                  try
42                  {
43                      if (lbf.isSingleton(name))
44                      {
45  
46                          Object bean = lbf.getBean(name);
47                          Class cls = AopUtils.getTargetClass(bean);
48  
49                          AvailableToPlugins annotation = AnnotationUtils.findAnnotation(cls, AvailableToPlugins.class);
50                          Class[] ifs;
51                          if (annotation != null) {
52                              if (annotation.value() != Void.class) {
53                                  ifs = new Class[] { annotation.value() };
54                              } else {
55                                  ifs = bean.getClass().getInterfaces();
56                              }
57                              registrar.register(ifs).forInstance(bean).withName(name);
58                          }
59                      }
60                  } catch (BeanIsAbstractException ex)
61                  {
62                      // skipping abstract beans (is there a better way to check for this?)
63                  }
64              }
65          }
66      }
67  }