利用Annotation来实现属性的注入

本文深入探讨了Spring框架中从手动装配到自动装配的转变,详细介绍了@Resource注解的原理及使用方法,包括如何在XML配置文件中声明组件,并通过注解实现组件之间的自动装配。通过对比手动装配和自动装配的不同,帮助开发者理解并掌握更高效的依赖注入方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在以前的SPRING中我们通常采用的方式是在XML文件来来实现手动装配类的属性从而来实现IOC。

例如

<bean id="personDao" class="com.dao.PersonDao"/>

 

<bean id="personService" class="com.service.PersonService">

    <property name="personDao">
        <ref bean="personDao" />
  </property>

</beam>

 

如果采用这种方式来进行装配,导致会是该XML十分的庞大和臃肿,在2.5中,可以采用@Resource的方式来进行自动装配。他的原理是首先来查找跟你标记属性名到XML文件中来找名字相同的,如果名字没有相同的再找类型相同的。

首先要做的工作:

1.加入Annotation所需要的命名空间(红色标记的)

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-2.5.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
 <context:annotation-config/>

2.在你的所需奥装配的类的属性上或是set 方法上加入@Resource标签

 

package com.service;

import javax.annotation.Resource;

import com.dao.IPersonDao;

public class PersonService implements IPersonService {

 @Resource(name="personDao")
 public IPersonDao personDao;
 public IPersonDao getPersonDao() {
  return personDao;
 }

//或者在set方法上标记也可以
 public void setPersonDao(IPersonDao personDao) {
  this.personDao = personDao;
 }
 public void getPerson() {
  this.personDao.getPerson();

 }

}

 

然后在配置文件中直接写:

<bean id="personDao" class="com.dao.PersonDao"/>

 

<bean id="personService" class="com.service.PersonService">

  </beam>

 

就可以了。

 他的原理跟.net中attribute的原理是类似的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值