title: Implement custom annotation in Spring
body: <p>I want to implement an annotation which registers classes (not instances of classes) with a factory as soon as the application is started. I am using Spring Framework 4.2.7.</p>
  
  <p>Consider a system with a dashboard and multiple widgets. The dashboard has a configuration file which contains a list of widgets to display for the current user. When displayed it reads the configuration and creates the widgets. The widgets will receive additional parameters from the configuration.</p>
  
  <p>Here is a bit of code illustrating this:</p>
  
  <pre><code>public class TestDashboard implements Dashboard {
      public void dashboardPreDisplay() {
          List&lt;String&gt; widgets = getWidgetList(/* current user in session */);
          for (String widgetId : widgets) {
              // create instance of DashboardWidget with given ID
              DashboardWidget x = widgetFactory.createWidget(widgetId);
          }
      }
  
      public List&lt;String&gt; getWidgetList(String user) {
          // load list of IDs of DashboardWidgets to be displayed for the user
      }
  
      @Autowired
      private WidgetFactory widgetFactory;
  }
  
  @Service
  public class WidgetFactory {
      public DashboardWidget createWidget(String widgetId) {
          // look up Class&lt;&gt; of DashboardWidget with given id in widgetClasses
          // construct and initialize DashboardWidget
      }
  
      private HashMap&lt;String, Class&lt;?&gt;&gt; widgetClasses;
  }
  </code></pre>
  
  <p>When implementing my widgets I don't want to deal with registering the widget with the factory class. Ideally I would just annotate the widget like that:</p>
  
  <pre><code>@DashboardWidget(id = "uniqueId")
  public class DashboardWidgetA implements DashboardWidget {
      // ...
  }
  </code></pre>
  
  <p>When the application starts it should scan the classpath for <code>@DashboardWidget</code> annotations and register the classes with the factory, so that the widgets can be constructed by giving the createWidget-method the id of the widget.</p>
  
  <p>At the moment I am a little bit confused. I think Spring has every tool on board to achieve this behavior. But I cannot think of a way how to do it. </p>
  
  <p>Do you have some advice for me?</p>