我们以及知道怎么通过spring创建Bean对象了,但是我们清楚,一个类它不仅有属性还有一些特定的行为。那么专属于这些类的属性,在Sprin中我们将通过何种方式注入呢?
通常,JavaBean的属性是私有的,同时拥有一套存取器的方法,set和get方法。Spring就是借助属性的set方法来配置属性的值,这就是setter方式注入。
-
/**
-
* 运动员类,他有一个特殊的属性,该属性是对象
-
* @author liuyc
-
*
-
*/
-
public class Player {
-
private String name;
-
private String age;
-
private String subject;
-
private Trainer trainer;
-
public Player() {
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
public String getAge() {
-
return age;
-
}
-
public void setAge(String age) {
-
this.age = age;
-
}
-
public String getSubject() {
-
return subject;
-
}
-
public void setSubject(String subject) {
-
this.subject = subject;
-
}
-
public Trainer getTrainer() {
-
return trainer;
-
}
-
public void setTrainer(Trainer trainer) {
-
this.trainer = trainer;
-
}
-
}
-
/**
-
* 教练类
-
* @author liuyc
-
*
-
*/
-
public class Trainer {
-
private String name;
-
private String age;
-
private String subject;
-
public Trainer() {
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
public String getAge() {
-
return age;
-
}
-
public void setAge(String age) {
-
this.age = age;
-
}
-
public String getSubject() {
-
return subject;
-
}
-
public void setSubject(String subject) {
-
this.subject = subject;
-
}
-
}
配置好XML文件:
-
<?xml version="1.0" encoding="UTF-8"?>
-
<beans xmlns="http://www.springframework.org/schema/beans"
-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
-
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
<bean id="player" class="com.cm2easy.miki.example.chapter1.Player">
-
<property name="name" value="林丹" />
-
<property name="age" value="33" />
-
<property name="subject" value="羽毛球" />
-
<property name="trainer" ref="trainer" />
-
</bean>
-
<bean id="trainer" class="com.cm2easy.miki.example.chapter1.Trainer">
-
<property name="name" value="李永波"/>
-
<property name="age" value="54"/>
-
<property name="subject" value="羽毛球"/>
-
</bean>
-
</beans>
上述配置涉及了属性值是普通值和对象的属性注入。