概念
-
依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源
-
注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配
构造器注入
Set 注入
要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is
@Data
public class Address {
private String address;
}
@Data
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public void show(){
System.out.println("name="+ name
+ ",address="+ address.getAddress()
+ ",books="
);
for (String book:books){
System.out.print("<<"+book+">>\t");
}
System.out.println("\n爱好:"+hobbys);
System.out.println("card:"+card);
System.out.println("games:"+games);
System.out.println("wife:"+wife);
System.out.println("info:"+info);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--常量注入-->
<bean id="addr" class="com.yao.pojo.Address">
<property name="address" value="重庆"/>
</bean>
<!--Bean注入-->
<bean id="student" class="com.yao.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
</bean>
<bean id="student1" class="com.yao.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
<!--数组-->
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
<!--List-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>爬山</value>
</list>
</property>
<!--map-->
<property name="card">
<map>
<entry key="中国邮政" value="456456456465456"/>
<entry key="建设" value="1456682255511"/>
</map>
</property>
<!--set-->
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
<!--null-->
<property name="wife"><null/></property>
<!--properties-->
<property name="info">
<props>
<prop key="学号">20190604</prop>
<prop key="性别">男</prop>
<prop key="姓名">小明</prop>
</props>
</property>
</bean>
</beans>
p命名和c命名注入
- 需要在头文件中加入约束文件
- 需要注意把有参构造器加上,这里也能知道,c 就是所谓的构造器注入
<?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"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<!--需要空构造器-->
<bean id="user" class="com.yao.pojo.User" p:name="狂神" p:age="18"/>
<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<!--需要有参构造器-->
<bean id="user2" class="com.yao.pojo.User" c:name="狂神" c:age="18"/>
</beans>