Spring 3.1中对JSR-330的支持

来源:互联网 发布:关于网络诈骗的作文800 编辑:程序博客网 时间:2024/04/24 22:18
JSR-330其实是一种注入的标准了,详细参考http://www.jcp.org/en/jsr/detail?id=330 
  在spring 3.1中,可以使用@Inject,@Named 这两个注解去实现注入,其中 
@Inject等于@Autowired ,@Named等于@component。结合各类资料,小结 
如下: 

1) 首先加入jar到pom.xml 
 
[java] view plain copy
  1. <dependency>  
  2.         <groupId>javax.inject</groupId>  
  3.         <artifactId>javax.inject</artifactId>  
  4.         <version>1</version>  
  5.     </dependency>  


2) 使用JSR-330 
 
[java] view plain copy
  1.    
  2. import javax.inject.Named;  
  3.    
  4. @Named  
  5. public class CustomerDAO   
  6. {  
  7.    
  8.     public void save() {  
  9.         System.out.println("CustomerDAO save method...");  
  10.     }     
  11. }  


  这是一个DAO,然后在service中,看下如何注入: 
[java] view plain copy
  1. @Named  
  2. public class CustomerService   
  3. {  
  4.     @Inject  
  5.     CustomerDAO customerDAO;  
  6.    
  7.     public void save() {  
  8.    
  9.         System.out.println("CustomerService save method...");  
  10.         customerDAO.save();  
  11.    
  12.     }  
  13.    
  14. }  


3 spring注解和jsr-330都是要配置下 

<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.mkyong.customer" /> 

</beans> 

4 jsr-330的限制 
   @Inject 没有@required属性去确保成功注入 
在spring 中,默认@inject的scope是singleon的,当然可以用@scope去另外改 
对于@Value, @Required  @Lazy,JSR-330都没对应的东西了 
0 0