文章目录
属性注入是通过
bean
标签中的property
标签来实现的。
1. Bean注入
通过property
标签中的ref
属性来实现。
1.1 Bean定义
@Data
public class User {
// 该属性是一个Class
private Cat cat;
}
@Data
public class Cat {
private String name;
private String color;
}
1.2 Bean注入
<bean class="com.learning.spring.ioc.User" id="user">
<!--通过ref属性来注入关联的Bean-->
<property name="cat" ref="cat"/>
</bean>
<bean class="com.learning.spring.ioc.Cat" id="cat">
<property name="name" value="小白"/>
<property name="color" value="白色"/>
</bean>
2. 数组注入
2.1 Bean定义
@Data
public class User {
private Cat[] cats;
private String[] books;
}
2.2 数组注入
<bean class="com.learning.spring.ioc.Cat" id="cat1">
<property name="name" value="小白"/>
<property name="color" value="白色"/>
</bean>
<bean class="com.learning.spring.ioc.Cat" id="cat2">
<property name="name" value="小黑"/>
<property name="color" value="黑色"/>
</bean>
<bean class="com.learning.spring.ioc.User" id="user">
<!--通过ref-->
<property name="cats">
<array>
<ref bean="cat1"/>
<ref bean="cat2"/>
</array>
</property>
<property name="books">
<array>
<value>水浒传</value>
<value>西游记</value>
</array>
</property>
</bean>
3. Map注入
3.1 Bean定义
@Data
public class User {
private Map<String, String> books;
}
3.2 Map注入
<bean class="com.learning.spring.ioc.User" id="user">
<property name="books">
<map>
<entry key="name" value="小花"/>
<entry key="age" value=" 23"/>
</map>
</property>
</bean>
4. List注入
4.1 Bean定义
@Data
public class User {
private List<String> bookNames;
}
4.2 List注入
<bean class="com.learning.spring.ioc.User" id="user">
<property name="bookNames">
<list>
<value type="java.lang.String">小花</value>
<value type="java.lang.String">小树</value>
</list>
</property>
</bean>
5. Set注入
5.1 Bean定义
@Data
public class User {
private Set<String> bookNames;
}
5.2 Set注入
<bean class="com.learning.spring.ioc.User" id="user">
<property name="bookNames">
<set>
<value type="java.lang.String">小花</value>
<value type="java.lang.String">小树</value>
</set>
</property>
</bean>
6. Properties注入
6.1 Bean定义
@Data
public class User {
private Properties info;
}
6.2 Properties注入
<bean class="com.learning.spring.ioc.User" id="user">
<property name="info">
<props>
<prop key="name">admin</prop>
<prop key="age">23</prop>
</props>
</property>
</bean>