Close

Spring - Using @Inject annotation on setter methods

package com.logicbig.example;


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

import javax.inject.Inject;

public class Greeter {
  private GreetingService greetingService;

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

  public void showGreeting(String name) {
      System.out.println(greetingService.getGreeting(name));
  }
}
@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.
  • javax.inject 1: The javax.inject API.
  • JDK 1.8
  • Maven 3.6.3

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

    See also

    Spring - Defining Injection point by using @Inject annotation