The annotation @Autowired can be used to declare an injection point.
In other words, this annotation instructs the Spring container to find a registered bean of the same type as of the annotated type and perform dependency injection.
Example
@Autowired can be used at various places. Following example shows how to use it on a field.
package com.logicbig.example;
public class GreetingService {
public String getGreeting(String name) {
return "Hi there, " + name;
}
}
Using @Autowired
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
public class Greeter {
@Autowired
private GreetingService greetingService;
public void showGreeting(String name) {
System.out.println(greetingService.getGreeting(name));
}
}
Defining beans and running the example application
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppRunner {
@Bean
public GreetingService greetingService() {
return new GreetingService();
}
@Bean
public Greeter greeter() {
return new Greeter();
}
public static void main(String... strings) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppRunner.class);
Greeter greeter = context.getBean(Greeter.class);
greeter.showGreeting("Joe");
}
}
OutputHi there, Joe
@Autowire can also be used on setters , constructors and to any methods having multiple arguments.
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|