DEV Community

eidher
eidher

Posted on • Edited on

3

Autowiring in Spring

Constructor Injection

    @Autowired
    public AppServiceImpl(AppRepository appRepository) {
        this.appRepository = appRepository;
    }
Enter fullscreen mode Exit fullscreen mode

Method Injection

    @Autowired
    public setRepository(AppRepository appRepository) {
        this.appRepository = appRepository;
    }
Enter fullscreen mode Exit fullscreen mode

Field Injection

Not recommended. Hard to unit test.

    @Autowired
    private AppRepository appRepository;
Enter fullscreen mode Exit fullscreen mode

Optional dependencies

Only inject if dependency exists:

    @Autowired(required=false)
    AppService appService;

    public void method() {
      if(appService != null) {
        ...
      }
    }
Enter fullscreen mode Exit fullscreen mode

Using Optional:

    @Autowired
    Optional<AppService> appService;

    public void method() {
      appService.ifPresent(s -> {
        ...
      });
    }
Enter fullscreen mode Exit fullscreen mode

Qualifier Annotation

When component names are not specified, they are auto-generated. When specified, they allow disambiguation if more than one bean class implements the same interface.

@Component
public class AppServiceImpl implements AppService {
    @Autowired
    public AppServiceImpl(@Qualifier("jdbcRepository") AppRepository appRepository) {
        this.appRepository = appRepository;
    }
}

@Component("jdbcRepository")
public class JdbcRepositoryImpl implements AppRepository {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (2)

Collapse
 
kriska profile image
Kristina Gocheva

What are the advantages of autowiring? Would you recommended annotation configuration against xml configuration?

Collapse
 
eidher profile image
eidher • Edited

Autowiring requires less code, reduces development time, and is cleaner. XML configuration is a cumbersome and outdated form of configuration.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up