Close

Spring - Defining Injection point by using @Inject annotation

[Last Updated: Dec 2, 2020]

JSR 330’s javax.inject.@Inject annotation can be used in place of Spring’s @Autowired annotation

Starting with Spring 3.0, Spring offers support for JSR 330 standard annotations (Dependency Injection). Those annotations are scanned in the same way as the Spring annotations.

Example

package com.logicbig.example;


public class GreetingService {
  public String getGreeting(String name) {
      return "Hi there, " + name;
  }
}

Using @Inject annotation

package com.logicbig.example;

import javax.inject.Inject;

public class Greeter {
  @Inject
  private GreetingService greetingService;

  public void showGreeting(String name){
      System.out.println(greetingService.getGreeting(name));
  }
}

Defining beans and running the example app

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.
  • javax.inject 1: The javax.inject API.
  • JDK 1.8
  • Maven 3.6.3

Spring - using JSR-330 @Inject annotation Select All Download
  • spring-inject-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Greeter.java

    See Also