注解@Resource实现机制

       spring3.X为我们引入了组件自动扫描机制,它可以在classPath路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进spring容器中管理。    

      首先说明一下注解的含义:     

     @Service用于标注业务层组件。

     @Controller用于标注控制层组件(如struts中的action)。

     @Repository用于标注数据访问组件,即DAO组件。

     @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

     使用Spring自动装备机制要在XML文件中配置以下信息:

     一、引入context的命名空间

<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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" default-lazy-init="true">
   二、在配置文件中添加context:component-scan标签

<context:component-scan base-package="com.***.controller" />
这样就可以在文件中使用注解了,以@Resource为例,有两种实现方式: 

   一、

<pre name="code" class="java">    //用在属性上
	@Resource(name = "newsService")
	private NewsService newsService;

   二、 
	//用于属性的set方法上  
	@Resource(name="newsDao")  
	public void setNews(NewsDao newsDao) { 
	  this.newsDao = newsDao;  
	} 
前者默认取字段的名称作为bean名称寻找依赖对象,后者默认取属性名作为bean名称寻找依赖对象。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值