Java-based vs annotation-based configuration/autowiring

Java based Configuration:

The official Spring documentation refers to configuring your beans using a Java class annotated with @Configuration and containing @Bean methods as 'Java Configuration'. This allows you to be absolutely free of all XML in your application (at least as far as Spring goes). This support was added in Spring 3.0, and has gotten more powerful.

Source

In other words, there is no configuration file required. If everything is fine with your application.

Annotation based Configuration:

Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

Source

In other words, there are XML configuration files yet but bean wiring, is configured using annotations.
Note: Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches.
Note: Annotation wiring is not turned on in the Spring container by default. So, we can use annotation-based wiring, we will need to enable it in our Spring configuration file.


They are similar, but have subtle differences.

Instead of having an @Component annotation on your class( which is annotation-based configuration ), you can skip the @Component and instead have a @Bean annotated method which returns a new instance of this class.( this is Java-based configuration).

For the simplest of applications, it doesn't make a difference but it affects stuff like "Dynamic subclassing during lookup method injection" where if you had the @Lookup annotation on a abstract method, Spring automatically does magic and overrides this abstract method to return a @Component annotated bean.

Spring cannot do this automatic subclassing for methods which reference @Bean beans. In this case, you need to manually override the method using your own subclass.

You can find basic code examples in the Spring reference. https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-lookup-method-injection

Tags:

Spring