Close

Spring - Using @Autowired annotation on arbitrary methods

[Last Updated: Dec 5, 2020]

@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 appStartTime) {
      greetingFormat = String.format("%s. This app is running since: %s%n", greetingService.getGreeting("<NAME>"),
              appStartTime.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.LocalDateTime;

@Configuration
public class AppRunner {

  @Bean
  public GreetingService greetingService() {
      return new GreetingService();
  }

  @Bean
  public LocalDateTime appStartTime(){
      return LocalDateTime.now();
  }

  @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");
  }
}

Output

Hi there, Joe. This app is running since: 2020-Dec-5

Example Project

Dependencies and Technologies Used:

  • spring-context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Using @Autowired on methods other than constructors and setters Select All Download
  • spring-using-autowire-annotation-on-arbitrary-methods
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Greeter.java

    See Also