Autowiring Services

Annocon offers functionality to find and link collaborating services automatically. Autowiring can save coding effort by injecting service references into instances without explicitly defining the references. The manual setting of the properties can be substituted by a call to the AutowiringUtil class.

Autowiring by type

The next example shows autowiring by type:

  @Service(id = "Calculator")
  public Calculator getCalculator()
  {
    Calculator calculator = new Calculator();
    AutowiringUtil.autowirePropertiesByType(this, calculator);
    return calculator;
  }   

The AutowiringUtil visits all writable properties (a setter method is present) of the calculator instance which are null. It searches for a service in the context (provided as "this") whose type matches the type of the property. Then a reference to the service is injected into the target by calling the setter method.

Full source code: AutowiringByTypeContext , Calculator

Autowiring by name

In the same manner it is possible to execute a autowiring by name:

@Context 
public class AutowiringByNameContext
{
  @Service(id = "ActionCaller")
  public AutowireTarget getActionCaller()
  {
    AutowireTarget caller = new AutowireTarget();
    AutowiringUtil.autowirePropertiesByName(this, caller);
    return caller;
  }

  @Service(id = "PrintAction")
  public Runnable getPrintAction()
  {
    return new Thread("PrintAction");
  }

  @Service(id = "StartAction")
  public Runnable getStartAction()
  {
    return new Thread("StartAction");
  }

}      

In this case annocon searches for services whose ids match the property names of the autowiring target. That is 'PrintAction' and 'StartAction' (note the leading uppercase letter).

public class ActionCaller
{
  public void setPrintAction(Runnable printAction)
  {
    _printAction = printAction;
  }
  
  public void setStartAction(Runnable startAction)
  {
    _startAction = startAction;
  }
}      

Full source code: AutowiringByNameContext , ActionCaller

Wiring external objects

The autowiring support of annocon is very flexible and not restricted to the service creation inside of a context class. It is rather possible to wire arbitrary objects by referencing a valid annocon context:

ContextFactory factory = new ContextFactory();
BasicContext context = (BasicContext) factory.buildContext(BasicContext.class);

Calculator anotherCalculator = new Calculator();
AutowiringUtil.autowirePropertiesByType(context, anotherCalculator);
     

This can be used for example to wire all struts actions of an application. A custom RequestProcessor would just hand over the action instances to the AutowiringUtil:

ApplicationContext context = (ApplicationContext) request.getServletContext().getAttribute("mycontext");
Action action = processActionCreate(request, response, mapping);
AutowiringUtil.autowirePropertiesByType(context, action);
     

Continue to service configuration.