Spring - Defining Injection point by using @Inject annotation
Bài viết gốc xem tại : https://www.logicbig.com/tutorials/spring-framework/spring-core/defining-injection-point-by-using-inject-annotation.html
javax.inject.@Inject
Chú thích của JSR 330 có thể được sử dụng thay thế cho chú thích @Autowired mong muốn của Spring
Bắt đầu với Spring 3.0, Spring cung cấp hỗ trợ cho JSR 330chú thích tiêu chuẩn (Dependency Injection). Các chú thích đó được quét theo cách giống như các chú thích của Spring annotations.
Thí dụ
package com.logicbig.example;
public class GreetingService {
public String getGreeting(String name) {
return "Hi there, " + name;
}
}
Sử dụng @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)); } }
Xác định bean và chạy ứng dụng mẫu
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
Bình luận