1. 獲取Bean
XML文件:
<bean id="helloworld" class="org.kkk.spring6.bean.HelloWorld"></bean>
1.1 根據(jù)id獲取
@Test
public void testHelloWorld(){
//加載XML文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//根據(jù)id獲取Bean對象
HelloWorld bean = context.getBean("helloworld");
//調(diào)用該對象的方法
bean.sayHello();
}
1.2 根據(jù)類型獲取
@Test
public void testHelloWorld(){
//加載XML文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//根據(jù)類型獲取Bean對象
HelloWorld bean = context.getBean(helloworld.class);
//調(diào)用該對象的方法
bean.sayHello();
}
1.3 根據(jù)id和類型獲取
@Test
public void testHelloWorld(){
//加載XML文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//根據(jù)類型獲取Bean對象
HelloWorld bean = context.getBean("helloworld", helloworld.class);
//調(diào)用該對象的方法
bean.sayHello();
}
注意:
-
當(dāng)根據(jù)類型獲取bean時,要求IOC容器中指定類型的bean有且只能有一個。
例如以下XML文件,當(dāng)IOC容器中一共配置了兩個,根據(jù)類型獲取時會拋出異常。
<bean id="helloworldOne" class="org.kkk.spring6.bean.HelloWorld"></bean>
<bean id="helloworldTwo" class="org.kkk.spring6.bean.HelloWorld"></bean>
-
根據(jù)類型來獲取bean時,在滿足bean唯一性的前提下,其實只是看:『對象 instanceof 指定的類型』的返回結(jié)果,只要返回的是true就可以認(rèn)定為和類型匹配,能夠獲取到。
因此,如果一個接口有多個實現(xiàn)類,這些實現(xiàn)類都配置了 bean,根據(jù)接口類型就不可以獲取到 bean ,因為不滿足唯一性。而如果這個接口只有一個實現(xiàn)類,那就可以獲取到。
2. 依賴注入
個人理解:依賴注入就是為對象的屬性賦值
2.1 setter注入
通過組件類的setXxx()方法給組件對象設(shè)置屬性
①創(chuàng)建學(xué)生類Student
package org.kkk.spring6.bean;
public class Student {
private Integer id;
private String name;
private Integer age;
private String sex;
public Student() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
②配置bean時為屬性賦值
spring-di.xml
<bean id="student" class="org.kkk.spring6.bean.Student">
<!-- property標(biāo)簽:通過組件類的setXxx()方法給組件對象設(shè)置屬性 -->
<!-- name屬性:指定屬性名(這個屬性名是getXxx()、setXxx()方法定義的,和成員變量無關(guān)) -->
<!-- value屬性:指定屬性值 -->
<property name="id" value="1001"></property>
<property name="name" value="張三"></property>
<property name="age" value="23"></property>
<property name="sex" value="男"></property>
</bean>
③測試
@Test
public void testDIBySet(){
ApplicationContext context= new ClassPathXmlApplicationContext("spring-di.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student);
}
2.2 構(gòu)造器注入
通過組件類的有參構(gòu)造方法給組件對象設(shè)置屬性
①在Student類中添加有參構(gòu)造
public Student(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
②配置bean
spring-di.xml
<bean id="student" class="org.kkk.spring6.bean.Student">
<constructor-arg value="1002"></constructor-arg>
<constructor-arg value="李四"></constructor-arg>
<constructor-arg value="33"></constructor-arg>
<constructor-arg value="女"></constructor-arg>
</bean>
注意:
constructor-arg標(biāo)簽還有兩個屬性可以進(jìn)一步描述構(gòu)造器參數(shù):
- index屬性:指定參數(shù)所在位置的索引(從0開始)
- name屬性:指定參數(shù)名
③測試
@Test
public void testDIByConstructor(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-di.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student);
}
2.3 特殊值處理
在為屬性進(jìn)行賦值時,可能會出現(xiàn)一些特殊情況要特殊處理。
①null值
<property name="name">
<null />
</property>
注意:
<property name="name" value="null"></property>
以上寫法,為name所賦的值是字符串null
②xml實體
<!-- 小于號在XML文檔中用來定義標(biāo)簽的開始,不能隨便使用 -->
<!-- 解決方案一:使用XML實體來代替 -->
<property name="expression" value="a < b"/>
③CDATA節(jié)
<property name="expression">
<!-- 解決方案二:使用CDATA節(jié) -->
<!-- CDATA中的C代表Character,是文本、字符的含義,CDATA就表示純文本數(shù)據(jù) -->
<!-- XML解析器看到CDATA節(jié)就知道這里是純文本,就不會當(dāng)作XML標(biāo)簽或?qū)傩詠斫馕?-->
<!-- 所以CDATA節(jié)中寫什么符號都隨意 -->
<value><![CDATA[a < b]]></value>
</property>
2.4 為對象類型屬性賦值
當(dāng)某一個類存在類型為另外一個類的屬性時,就不能按照上述一般情況對這個屬性賦值。例如,現(xiàn)在有學(xué)生類和班級類,為了表示學(xué)生和班級的關(guān)系,學(xué)生類中有一個班級類的屬性。
代碼表示如下:
班級類Clazz
package org.kkk.spring6.bean
public class Clazz {
private Integer clazzId;
private String clazzName;
public Integer getClazzId() {
return clazzId;
}
public void setClazzId(Integer clazzId) {
this.clazzId = clazzId;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
@Override
public String toString() {
return "Clazz{" +
"clazzId=" + clazzId +
", clazzName='" + clazzName + '\'' +
'}';
}
public Clazz() {
}
public Clazz(Integer clazzId, String clazzName) {
this.clazzId = clazzId;
this.clazzName = clazzName;
}
}
Student類
在Student類中添加以下代碼:
private Clazz clazz;
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
可以看到,學(xué)生類中有一個屬性為clazz,其類型為班級類。我們對clazz進(jìn)行屬性賦值,有以下幾種方法。
①外部bean
配置Clazz類型的bean:
<bean id="clazz" class="org.kkk.spring6.bean.Clazz">
<property name="clazzId" value="1001"></property>
<property name="clazzName" value="c++開發(fā)培訓(xùn)班"></property>
</bean>
為Student中的clazz屬性賦值:
<bean id="student" class="org.kkk.spring6.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref屬性:引用IOC容器中某個bean的id,將所對應(yīng)的bean為屬性賦值 -->
<property name="clazz" ref="clazz"></property>
</bean>
如果錯把ref屬性寫成了value屬性,會拋出異常: Caused by: java.lang.IllegalStateException: Cannot convert value of type ‘java.lang.String’ to required type ‘org.kkk.spring6.bean.Clazz’ for property ‘clazz’: no matching editors or conversion strategy found
意思是不能把String類型轉(zhuǎn)換成我們要的Clazz類型,說明我們使用value屬性時,Spring只把這個屬性看做一個普通的字符串,不會認(rèn)為這是一個bean的id,更不會根據(jù)它去找到bean來賦值
② 內(nèi)部bean
<bean id="student" class="org.kkk.spring6.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<property name="clazz">
<!-- 在一個bean中再聲明一個bean就是內(nèi)部bean -->
<!-- 內(nèi)部bean只能用于給屬性賦值,不能在外部通過IOC容器獲取,因此可以省略id屬性 -->
<bean id="clazzInner" class="org.kkk.spring6.bean.Clazz">
<property name="clazzId" value="1001"></property>
<property name="clazzName" value="c++開發(fā)培訓(xùn)班"></property>
</bean>
</property>
</bean>
③ 級聯(lián)屬性賦值
<bean id="student" class="org.kkk.spring6.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<property name="clazz" ref="clazzOne"></property>
<property name="clazz.clazzId" value="1001"></property>
<property name="clazz.clazzName" value="c++開發(fā)培訓(xùn)班"></property>
</bean>
2.5 為數(shù)組類型屬性賦值
①修改Student類
在Student類中添加以下代碼:
private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
②配置bean
<bean id="student" class="org.kkk.spring.bean6.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref屬性:引用IOC容器中某個bean的id,將所對應(yīng)的bean為屬性賦值 -->
<property name="clazz" ref="clazz"></property>
<property name="hobbies">
<array>
<value>吃飯</value>
<value>睡覺</value>
<value>寫代碼</value>
</array>
</property>
</bean>
2.6 為集合類型屬性賦值
①為List集合類型屬性賦值
在Clazz類中添加以下代碼:
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
配置bean:
<bean id="clazz" class="org.kkk.spring6.bean.Clazz">
<property name="clazzId" value="1002"></property>
<property name="clazzName" value="Java開發(fā)培訓(xùn)班"></property>
<property name="students">
<list>
<ref bean="studentOne"></ref>
<ref bean="studentTwo"></ref>
<ref bean="studentThree"></ref>
</list>
</property>
</bean>
若為Set集合類型屬性賦值,只需要將其中的list標(biāo)簽改為set標(biāo)簽即可
②為Map集合類型屬性賦值
創(chuàng)建教師類Teacher:
package org.kkk.spring6.bean;
public class Teacher {
private Integer teacherId;
private String teacherName;
public Integer getTeacherId() {
return teacherId;
}
public void setTeacherId(Integer teacherId) {
this.teacherId = teacherId;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Teacher(Integer teacherId, String teacherName) {
this.teacherId = teacherId;
this.teacherName = teacherName;
}
public Teacher() {
}
@Override
public String toString() {
return "Teacher{" +
"teacherId=" + teacherId +
", teacherName='" + teacherName + '\'' +
'}';
}
}
在Student類中添加以下代碼:
private Map<String, Teacher> teacherMap;
public Map<String, Teacher> getTeacherMap() {
return teacherMap;
}
public void setTeacherMap(Map<String, Teacher> teacherMap) {
this.teacherMap = teacherMap;
}
配置bean:
<bean id="teacherOne" class="org.kkk.spring6.bean.Teacher">
<property name="teacherId" value="1005"></property>
<property name="teacherName" value="大寶"></property>
</bean>
<bean id="teacherTwo" class="org.kkk.spring6.bean.Teacher">
<property name="teacherId" value="1006"></property>
<property name="teacherName" value="二寶"></property>
</bean>
<bean id="studentFour" class="org.kkk.spring6.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref屬性:引用IOC容器中某個bean的id,將所對應(yīng)的bean為屬性賦值 -->
<property name="clazz" ref="clazzOne"></property>
<property name="hobbies">
<array>
<value>吃飯</value>
<value>睡覺</value>
<value>寫代碼</value>
</array>
</property>
<property name="teacherMap">
<map>
<entry>
<key>
<value>1005</value>
</key>
<ref bean="teacherOne"></ref>
</entry>
<entry>
<key>
<value>1006</value>
</key>
<ref bean="teacherTwo"></ref>
</entry>
</map>
</property>
</bean>
③引用集合類型的bean
<!--list集合類型的bean-->
<util:list id="students">
<ref bean="studentOne"></ref>
<ref bean="studentTwo"></ref>
<ref bean="studentThree"></ref>
</util:list>
<!--map集合類型的bean-->
<util:map id="teacherMap">
<entry>
<key>
<value>1005</value>
</key>
<ref bean="teacherOne"></ref>
</entry>
<entry>
<key>
<value>1006</value>
</key>
<ref bean="teacherTwo"></ref>
</entry>
</util:map>
<bean id="clazzTwo" class="org.kkk.spring6.bean.Clazz">
<property name="clazzId" value="1002"></property>
<property name="clazzName" value="Java開發(fā)培訓(xùn)班"></property>
<property name="students" ref="students"></property>
</bean>
<bean id="studentFour" class="org.kkk.spring6.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref屬性:引用IOC容器中某個bean的id,將所對應(yīng)的bean為屬性賦值 -->
<property name="clazz" ref="clazzOne"></property>
<property name="hobbies">
<array>
<value>吃飯</value>
<value>睡覺</value>
<value>寫代碼</value>
</array>
</property>
<property name="teacherMap" ref="teacherMap"></property>
</bean>
使用util:list、util:map標(biāo)簽必須引入相應(yīng)的命名空間
<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
2.7 p命名空間
引入p命名空間
<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
引入p命名空間后,可以通過以下方式為bean的各個屬性賦值
<bean id="student" class="org.kkk.spring6.bean.Student"
p:id="1006" p:name="小明" p:clazz-ref="clazzOne" p:teacherMap-ref="teacherMap"></bean>
2.8 引入外部屬性文件
①加入依賴
<!-- MySQL驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 數(shù)據(jù)源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
②創(chuàng)建外部屬性文件
文件jdbc.properties保存數(shù)據(jù)庫連接信息
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
③引入屬性文件
引入context 名稱空間
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
<!-- 引入外部屬性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
注意:在使用 context:property-placeholder 元素加載外包配置文件功能前,首先需要在 XML 配置的一級標(biāo)簽 中添加 context 相關(guān)的約束。
④配置bean
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
⑤測試
@Test
public void testDataSource() throws SQLException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-datasource.xml");
DataSource dataSource = context.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
2.9 bean的作用域
①概念
在Spring中可以通過配置bean標(biāo)簽的scope屬性來指定bean的作用域范圍,各取值含義參加下表:
取值 | 含義 | 創(chuàng)建對象的時機(jī) |
---|---|---|
singleton(默認(rèn)) | 在IOC容器中,這個bean的對象始終為單實例 | IOC容器初始化時 |
prototype | 這個bean在IOC容器中有多個實例 | 獲取bean時 |
如果是在WebApplicationContext環(huán)境下還會有另外幾個作用域(但不常用):
取值 | 含義 |
---|---|
request | 在一個請求范圍內(nèi)有效 |
session | 在一個會話范圍內(nèi)有效 |
②創(chuàng)建類User
package org.kkk.spring6.bean;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
③配置bean
<!-- scope屬性:取值singleton(默認(rèn)值),bean在IOC容器中只有一個實例,IOC容器初始化時創(chuàng)建對象 -->
<!-- scope屬性:取值prototype,bean在IOC容器中可以有多個實例,getBean()時創(chuàng)建對象 -->
<bean class="org.kkk.spring6.bean.User" scope="prototype"></bean>
④測試
@Test
public void testBeanScope(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-scope.xml");
User user1 = context.getBean(User.class);
User user2 = context.getBean(User.class);
System.out.println(user1==user2);
}
如果將scope屬性設(shè)置為singleton(單例)時,那么user1與user2的地址相同,兩者實質(zhì)上是同一個實例對象。如果scope屬性為prototype(多例),那么user1與user2的地址不同。
2.10 基于xml自動裝配
自動裝配:
根據(jù)指定的策略,在IOC容器中匹配某一個bean,自動為指定的bean中所依賴的類類型或接口類型屬性賦值
①場景模擬
創(chuàng)建類UserController
package org.kkk.spring6.autowire.controller
public class UserController {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void saveUser(){
userService.saveUser();
}
}
創(chuàng)建接口UserService
package org.kkk.spring6.autowire.service
public interface UserService {
void saveUser();
}
創(chuàng)建類UserServiceImpl實現(xiàn)接口UserService
package org.kkk.spring6.autowire.service.impl
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void saveUser() {
userDao.saveUser();
}
}
創(chuàng)建接口UserDao
package org.kkk.spring6.autowire.dao
public interface UserDao {
void saveUser();
}
創(chuàng)建類UserDaoImpl實現(xiàn)接口UserDao
package org.kkk.spring6.autowire.dao.impl
public class UserDaoImpl implements UserDao {
@Override
public void saveUser() {
System.out.println("保存成功");
}
}
②配置bean
使用bean標(biāo)簽的autowire屬性設(shè)置自動裝配效果
自動裝配方式:byType
byType:根據(jù)類型匹配IOC容器中的某個兼容類型的bean,為屬性自動賦值
若在IOC中,沒有任何一個兼容類型的bean能夠為屬性賦值,則該屬性不裝配,即值為默認(rèn)值null
若在IOC中,有多個兼容類型的bean能夠為屬性賦值,則拋出異常NoUniqueBeanDefinitionException
<bean id="userController" class="org.kkk.spring6.autowire.controller.UserController" autowire="byType"></bean>
<bean id="userService" class="org.kkk.spring6.autowire.service.impl.UserServiceImpl" autowire="byType"></bean>
<bean id="userDao" class="org.kkk.spring6.autowire.dao.impl.UserDaoImpl"></bean>
自動裝配方式:byName
byName:將自動裝配的屬性的屬性名,作為bean的id在IOC容器中匹配相對應(yīng)的bean進(jìn)行賦值文章來源:http://www.zghlxwxcb.cn/news/detail-823277.html
<bean id="userController" class="org.kkk.spring6.autowire.controller.UserController" autowire="byName"></bean>
<bean id="userService" class="org.kkk.spring6.autowire.service.impl.UserServiceImpl" autowire="byName"></bean>
<bean id="userServiceImpl" class="org.kkk.spring6.autowire.service.impl.UserServiceImpl" autowire="byName"></bean>
<bean id="userDao" class="org.kkk.spring6.autowire.dao.impl.UserDaoImpl"></bean>
<bean id="userDaoImpl" class="org.kkk.spring6.autowire.dao.impl.UserDaoImpl"></bean>
③測試文章來源地址http://www.zghlxwxcb.cn/news/detail-823277.html
@Test
public void testAutoWireByXML(){
ApplicationContext context = new ClassPathXmlApplicationContext("autowire-xml.xml");
UserController userController = context.getBean(UserController.class);
userController.saveUser();
}
到了這里,關(guān)于spring(1):基于XML獲取Bean對象以及各種依賴注入方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!