全文共 325 个字

JSR330是Jcp给出的官方标准反向依赖注入规范。Java大部分反向依赖注入的工具或者框架目前基本上都满足JSR330规范、例如spring、guice以及Dagger。

以我们最常用的spring为例。

JSR中@Inject可以当做@AutoWired来使用。而@Named可以当做@Component来使用。

使用JSR330首先要引入javax.inject包:

<dependency>  
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency> 

目前Maven中央仓库中就一个inject的jar。

首先使用xml配置通过注解扫描添加bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">  
    <context:component-scan  base-package="com.demo.jsr330"/>
</beans>  

然后像下面这个添加一个bean

@Named  
public class service {
  public  void   print(){
     System.out.println("Service  print  method is invoked");  
  }  
}  

然后将这个bean注入到其他bean中去使用

@Named  
public class Faction {
  @Inject
  Service service;

  public  void  show(){
     service.print(); 
  }  
}  

JSR330还定义了@Qualifier@Provider,对应到spring都给出了标准的实现。

使用JSR330代替原注解的好处是无论使用任何反向依赖注入工具或框架,只要他是支持JSR330的,都可以平滑的切换。