@Autowired annotation can be used on the methods with arbitrary names and multiple arguments:
@Autowired
public void configure(GreetingService greetingService, LocalDateTime appStartTime) {
....
}
Example
package com.logicbig.example;
public class GreetingService {
public String getGreeting(String name) {
return "Hi there, " + name;
}
}
Using @Autowired at arbitrary methods
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Greeter {
private String greetingFormat;
@Autowired
public void configure(GreetingService greetingService, LocalDateTime appServiceTime) {
greetingFormat = String.format("%s. This app is running since: %s%n", greetingService.getGreeting("<NAME>"),
appServiceTime.format(DateTimeFormatter.ofPattern("YYYY-MMM-d")));
}
public void showGreeting(String name) {
System.out.printf(greetingFormat.replaceAll("<NAME>", name));
}
}
Defining beans and running the example
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Configuration
public class AppRunner {
@Bean
public GreetingService greetingService() {
return new GreetingService();
}
@Bean
public LocalDateTime appServiceTime() {
return LocalDate.of(2021, 3, 1).atStartOfDay();
}
@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. This app is running since: 2021-Mar-1
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
|