Why do I need a setter for autowired / injected field?

GarfieldKlon picture GarfieldKlon · Nov 2, 2012 · Viewed 11.2k times · Source

I have a bean:

    <bean id="BasketLogic" class="efco.logic.EfcoBasketLogic" autowire="byType">
        <property name="documentLogic" ref="DocumentLogic" />
        <property name="stateAccess" ref="StateAccess" />
        <property name="contextAccess" ref="ContextAccess" />
    </bean>

  <bean id="EfcoErpService" autowire="byType" class="efco.erp.service.EfcoErpServiceImpl">
    <constructor-arg ref="ErpConnector"/>
  </bean>

documentLogic, stateAccess and contextAccess are fields on BasketLogicImpl

And I do not have <context:component-scan />

EfcoBasketLogic.java:

public class EfcoBasketLogic extends BasketLogicImpl {

        @Inject
        private EfcoErpService erpService;
    ...
    ...
    ...
}

erpService is null, unless I provide a setter. But why? I thought a setter isn't needed where autowiring is taking place? Could it be that BasketLogicImpl is responsible for that?

Answer

mrembisz picture mrembisz · Nov 2, 2012

You need to use a setter because annotations are not detected unless spring is told so through either <context:component-scan /> or <context:annotation-config />. Setter is detected because you specified autowire="byType".

You may find this question and answer helpful as well: When to use autowiring in Spring