Spring配置文件,DI 3、创建对象的方式 4、xml配置 5、依赖注入DI 6、Bean作用域(bean scope) 7、Bean自动装配
目录
3.1、无参构造方法
<bean >
<property name="name" value="张三"></property>
</bean>
3.2、有参构造方法
(1)使用属性名创建
<bean >
<constructor-arg name="name" value="张三"></constructor-arg>
</bean>
(2)使用参数下标创建
<bean >
<constructor-arg index="0" value="张三"></constructor-arg>
</bean>
(3)使用属性类型创建(不建议使用)
存在问题:①可能数据类型写错;②可能有多个相同类型的属性
<bean >
<constructor-arg type="java.lang.String" value="张三"></constructor-arg>
</bean>
4、xml配置
4.1、bean
<bean ></bean>
id:自定义的变量名
class:bean对象的全限定名(包名+类名)
name:取别名,比alias高级,可以用空格|逗号|混搭取多个别名
4.2、alias
<alias name="user" alias="uu"></alias>
只能取一个别名
4.3、import
<import resource="beans.xml"></import>
<import resource="beans1.xml"></import>
合并其他的配置文件
5、依赖注入DI
以前的理解:依赖注入就是注入对象的时候,连同他的依赖关系一同注入。
目前:分开解释
依赖:bean对象的创建依赖容器
注入:bean对象中的属性由容器注入
5.1、构造器注入
3中以及实现过
5.2、属性注入
属性注入的前提:必须要有set方法才能注入
pojo:Student
@Data
public class Student implements Serializable {
private String uname;
private Double[] scores;
private List<String> books;
private Teacher teacher;
private Set<String> subject;
private Map<String, String> map;
private String tube;
private Properties properties;
}
<bean >
<constructor-arg name="tid" value="0001"></constructor-arg>
<constructor-arg name="tname" value="李颖"></constructor-arg>
</bean>
<bean >
<!-- 普通属性注入:String -->
<property name="uname" value="张三"></property>
<!-- 数组注入 -->
<property name="scores">
<array>
<value>75.5</value>
<value>75.6</value>
<value>75.7</value>
</array>
</property>
<!-- list注入 -->
<property name="books">
<list>
<value>语文</value>
<value>数学</value>
<value>英语</value>
</list>
</property>
<!-- set注入 -->
<property name="subject">
<set>
<value>体育</value>
<value>音乐</value>
</set>
</property>
<!-- 对象注入 -->
<property name="teacher" ref="teacher"></property>
<!-- map注入 -->
<property name="map">
<map>
<entry key="音乐" value="肖恩"></entry>
</map>
</property>
<!-- null值注入 -->
<property name="tube">
<null/>
</property>
<!-- properties注入 -->
<property name="properties">
<props>
<prop key="driver">com.mysql.jdbc.Driver</prop>
<prop key="username">root</prop>
</props>
</property>
</bean>
5.3、拓展注入
p命名空间
<bean ></bean>
注意
(1)一定要先在xml文件中导入约束才能用
(2)类中一定要有无参构造方法,否则不能使用p命名空间
(3)和属性注入相同的操作
xmlns:p="http://www.springframework.org/schema/p"
c命名空间
<bean ></bean>
注意
(1)一定要先在xml文件中导入约束才能用
(2)类中一定要有有参构造方法,否则不能使用c命名空间
(3)和构造器注入相同的操作
xmlns:c="http://www.springframework.org/schema/c"
6、Bean作用域(bean scope)
7、Bean自动装配
7.1、byName
User.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private String name;
private Student student;
private Teacher teacher;
}
applicationContext.xml
<bean ></bean>
<bean ></bean>
<bean ></bean>
注意:
(1)id必须唯一,否则通过id的name装配的时候会报错
(2)byName装配是根据属性名与id对应查询装配的
(3)前提条件:id对应属性名,属性必须要要有set方法,否则结果均为null
7.2、byType
applicationContext.xml
<bean ></bean>
<bean ></bean>
<bean ></bean>
注意:
(1)id可以省略
(2)byType是根据属性的类型进行查找装配的
(3)如果有两个相同类型的话,依旧会报错