总结Spring Set注入方式,注解在set方法上,及对property标签的理解

Spring依赖注入主要的方式:1.Set方法注入;2.构造方法注入;3.接口注入。

依赖注入的涵义:通过Spring容器帮我们new指定实例并且将实例注入到需要该对象的类中。依赖注入的另一种说法是“控制反转”,通俗的理解是:平常我们new一个实例,这个实例的控制权是我们程序员,而控制反转是指new实例工作不由我们程序员来做而是交给spring容器来做。

平时主要用Set注入方式:假设有一个SpringAction,类中需要实例化一个SpringDao对象,那么就可以定义一个private的SpringDao成员变量,然后创建SpringDao的set方法(这是ioc的注入入口):

[html]  view plain  copy
  1. package com.springdemo.action;  
  2. public class SpringAction {  
  3.         //注入对象springDao  
  4.     private SpringDao springDao;  
  5.         //一定要写被注入对象的set方法  
  6.         public void setSpringDao(SpringDao springDao) {  
  7.         this.springDao = springDao;  
  8.     }  
  9.   
  10.  }  

随后编写spring的xml文件

<bean>中的name属性是class属性的一个别名,class属性指类的全名。
因为在SpringAction中有一个公共属性Springdao,所以要在<bean>标签中创建一个<property>标签指定SpringDao。<property>标签中的name就是SpringAction类中的SpringDao属性名,ref指<bean name="springDao"...>,
这样其实是spring将SpringDaoImpl对象实例化并且调用SpringAction的 setSpringDao方法将SpringDao注入
[html]  view plain  copy
  1. <!--配置bean,配置后该类由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(1)依赖注入,配置当前类中相应的属性-->  
  4.         <property name="springDao" ref="springDao"></property>  
  5.     </bean>  
  6. <bean name="springDao" class="com.springdemo.dao.impl.SpringDaoImpl"></bean>  

注意:通过Spring创建的对象默认是单例的,如果需要创建多实例对象可以在<bean>标签后面添加一个属性:

[html]  view plain  copy
  1. <bean name="..." class="..." scope="prototype">  

 

此外:对property name ref属性的理解:

[html]  view plain  copy
  1. <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"></bean>  
  2.   
  3. <bean id="userService" class="com.bjsxt.service.UserService">  
  4. <property name="userDAO" ref="u" />  



在com.bjsxt.service.UserService这个类中有个名为 userDAO 的属性,它的类型是com.bjsxt.dao.impl.UserDAO, 在spring初始化的时候把u 注入到UserService类中,相当于:

[html]  view plain  copy
  1. class UserService{  
  2. UserDAO userDAO = new UserDAOImpl();  
  3. }  


即该name指定了id中的某一个属性,将ref相关的类注入,将之new出来(绕了好半天...囧)



@Resource除了可以用在属性上,还可以用在set方法上。
例如:
@Resource private PersonDao personDao;
可以改成:
private PersonDao personDaoo;
@Resource或者@Resource(name="personDaoA")
public void setPersonDaoo(PersonDao personDaoo) {
this.personDaoo = personDaoo;
}
效果是一样的!

猜你喜欢

转载自blog.csdn.net/stackflow/article/details/79365310
今日推荐