一、构造器注入
二、Set方法注入
Person类的数据类型如下:
public class Person {
private int age;
private String name;
private String[] families;
private Address address;
private Set<String> games;
private Map<String,String> card;
private Properties pro;
}
其中的Address为类类型:
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
1、常量注入
即参数类型为八大基础数据类型和String类型,注入方式为:
<bean id="person" class="xyz.bryce.java.Person">
<!-- 1、常量注入-->
<property name="age" value="20"/>
<property name="name" value="bryce"/>
</bean>
2、类类型(bean)类型注入
因为要注入的属性又为一个类,所以不能直接通过value值的形式来赋值。
<bean id="person" class="xyz.bryce.java.Person">
<property name="address" ref="addr"/>
</bean>
其中ref
是链接到另一个bean
<bean id="addr" class="xyz.bryce.java.Address">
<property name="address" value="hubei-wuhan"/>
</bean>
3、数组注入
<bean id="person" class="xyz.bryce.java.Person">
<property name="families">
<array>
<value>mama</value>
<value>baba</value>
<value>gege</value>
</array>
</property>
</bean>
4、Set注入
<bean id="person" class="xyz.bryce.java.Person">
<property name="games">
<set>
<value>wangzhe</value>
<value>chiji</value>
</set>
</property>
<bean>
5、List注入
<property name="hobbys">
<list>
<value>music</value>
<value>running</value>
</list>
</property>
6、Map注入
<property name="card">
<map>
<entry key="ABC" value="132423"/>
<entry key="CCB" value="132645"/>
</map>
</property>
7、Properties注入
<property name="pro">
<props>
<prop key="student-id">2021233</prop>
<prop key="name">bryce</prop>
</props>
</property>
三、p、c命名空间注入
1、p命名空间注入
导入约束xmlns:p="http://www.springframework.org/schema/p"
p(properties)命名空间,属性依然要设置set方法。如果类中没有set方法,在p标签使用处就会显示错误。
<bean id="person" class="xyz.bryce.java.Person" p:age="20"/>
2、c命名空间注入
导入约束xmlns:p="http://www.springframework.org/schema/c"
p(Constructor)命名空间,属性依然要设置set方法,并且,还要有对应的有参构造器方法。
<bean id="person" class="xyz.bryce.java.Person" c:name="bryce"/>
例如要能写成上面这种,则在类中必须满足下面这两个条件:
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}