When to use autowiring in Spring

I believe there are two things confused here. What is meant by ‘autowiring’ in this chapter is marking bean for automated detection and injection of dependencies. This can be achieved through setting of “autowire” bean attribute.

This is in fact opposed to using @Autowired where you explicitely indicate field or setter for dependency injection.

Have a look here: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-autowire.

To explain it, assume you have

public class SnippetService {

    private TestService testService;

    public Snippet getSnippet() {
        return testService.getSnippet();
    }

    public void setTestService(TestService testService) {
      this.testService = testService;
    }
}

If you defined a bean:

<bean class="mypackage.SnippetService" autowire="byType"/>

spring would attempt to inject bean of matching type, TestService in this case, by calling setTestService setter. Even though you did not use @Autowired. This indeed is dangerous since some setters might not be meant to be called by spring.

If you set autowire=”no”, nothing will be injected unless marked so with @Autowired, @Resource, @Inject.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)