`

spring注入记载

 
阅读更多

近来有空整理一下项目中运用到的spring注解方式,发现很多注解都有类似的方法

现只整理项目中的一套方式:

例如:commonDao ;commonDaoImpl;commonService;commonServiceImpl 4个类,其中 commonDao和commonService是两个接口

 

1.将commonDao注入到commonDaoImpl 中:运用@Repository("commonDao") 完成 ,@Repository标签是用来给持久层的类定义一个名字

 

2.将commonService 注入 到commonServiceImpl中:运用@Service("commonService") ,@Service用于标注业务层组件

 

3.同时在commonServiceImpl中运用@Autowired 将dao类注入:

@Autowired
 private CommonDao commonDao; 

当接口存在两个实现类的时候必须使用@Qualifier指定注入哪个实现类,否则可以省略,只写@Autowired,例:

@Autowired

@Qualifier("commonDaoImpl1")  
 private CommonDao commonDao; 

 

其实还有一个泛意的注解:@Component ,用处是标注是spring管理的类;

在xml配置文件中定义

  <context:component-scan base-package="com.test.person"/>

它的作用和在xml文件中使用bean节点配置组件时一样的,使用自动扫描机制

 

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics