Spring4类属性自动装配和方法注入

来源:互联网 发布:淘宝客服培训班 编辑:程序博客网 时间:2024/06/05 23:53

1.自动装配(beans最外层头部标签里添加default-autowire =”xxx”)

xxx的取值
①byName

一个beanA(Person)中有属性是另外一个类对象(beanB如User),
依赖注入后,beanA类中定义的对象属性值会根据beanB注入命名比如为user来匹配对应的类对象User user。

public class Person {private String name;private User user;//此处的user在User对象注入bean时候命名id匹配}

②byType(如对象的类型User类)
如果在beans.xml中注入了同个类但是不同bean的id,会报错。
因为此时出现了同个类型的两个bean。

public class Person {private String name;private User user;//此处的User对象就是byType的根据}

③constructor
在Person中有构造方法,传入参数为User user,则如果beans.xml中有User类型的bean,会自动将其匹配到Person的构造方法中,赋值给user。

public class Person {private String name;private User user;public Person(User user) { //此处的User类就是constructor的//根据,会在bean中查找该类型的bean赋值,注意是根据类型,和id无关super();this.user = user;}}

2.方法注入

由于每个bean默认是单例,如果需要每次获取bean时候是不同的实例,则在bean的头部里面添加scope=”prototype”、

<bean id = "user" class = ''xx.xx.entity.User" scope = "prototype" />

如果其他类中有该属性

<bean id = "person" class = ''xx.xx.entity.Person"  >     <property name = "name" value = "xxx" />     <property name = "user" ref = "user" /></bean>

如果是以上的配置则会在Person中只有一个User对象而不是多个
要实现多个User对象
将Person写成抽象类 并且getUser的方法也是抽象方法
配置文件变为

<bean id = "person" class = ''xx.xx.entity.Person"  >     <property name = "name" value = "xxx" />     <lookup-method name ="getUser" bean = "user" /></bean>

就可以实现多个User对象实例。

3.方法替换

即如果Person中的getUser方法需要被其他类的方法替换(其实是对其属性user的赋值),获取到另外的值。比如是Person2类的方法,建立

public class Person2 implements MethodReplacer {//实现方法reimplement  //返回的是user类}

那么配置文件中

<bean id = "person" class = "xx.xx.entity.Person"  >     <property name = "name" value = "xxx" />     <replaced-method name ="getUser" replacer= "person2" /></bean><bean id = "person2" class = "xx.xx.entity.Person2"  />