Close

Spring Core - Using @Autowire annotation On a setter method

package com.logicbig.example;


public class GreetingService {

  public String getGreeting(String name) {
      return "Hi there, " + name;
  }
}
package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;

public class Greeter {

  private GreetingService greetingService;

  @Autowired
  public void setGreetingService(GreetingService greetingService) {
      this.greetingService = greetingService;
  }

  public void showGreeting(String name){
      System.out.println(greetingService.getGreeting(name));
  }
}
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");
  }
}

Output

Hi there, Joe

Example Project

Dependencies and Technologies Used:

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

spring-autowire-annotation-on-setter-example Select All Download
  • spring-autowire-annotation-on-setter-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Greeter.java

    See also

    Spring - Defining injection point by using @Autowire annotation