Monday, January 30, 2017

Java 依赖注入标准(JSR-330)CDI

JSR 330只是一种对DI的描述规范,就是用同一个的annotation来表示依赖,但具体实现由Spring或Guice来决定。

@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a bean.
@PostConstruct 类似于serverlet的init,bean产生->依赖注入->PostConstruct->service启动

@Named
public class Customer {
}

public class VideoApp {
@Inject
private Customer customer;

  @PostConstruct
  private void init(){
     System.out.println("postconstruct");
  }

}

Spring实现可以参考:
https://www.mkyong.com/spring3/spring-3-and-jsr-330-inject-and-named-example/


Spring的依赖注入


加入@Autowired后可以自动装配getter,setter就不用再写这些方法。
public class Zoo
{
    @Autowired
    private Tiger tiger;
 
    @Autowired
    private Monkey monkey;
 
    public String toString(){}
}

而Spring设置中只要加入<context:component-scan base-package="com.vtasters" />就会自动扫描vtasters这个包下所有注解,这样就不用在配置文件中声明bean了。

Guice的依赖注入

Guice完全用了Java依赖注入标准,也就是用了@Named, @Inject

ref:
Spring的注解
http://blog.csdn.net/DL88250/article/details/4838803#_Qualifier_9535574146353466_06

No comments:

Post a Comment