类型:
1、值类型
2、null (标签)
3、特殊符号 (< -> < )
4、CDATA
<?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-->
<bean id="school" class="com.gyk.ObjInject.School">
<property name="location" value="henan"></property>
<property name="num" value="30000"></property>
</bean>
<bean id="school2" class="com.gyk.ObjInject.School">
<property name="location" value="henan"></property>
<property name="num" value="30000"></property>
</bean>
<!-- <bean id="student" class="com.gyk.ObjInject.Student">-->
<!-- <property name="name" value="zs"></property>-->
<!-- <property name="age" value="22"></property>-->
<!-- <property name="school" ref="school"></property>-->
<!-- </bean>-->
<!-- 嵌套内部bean-->
<bean id="student" class="com.gyk.ObjInject.Student">
<property name="name" value="zs"></property>
<property name="age" value="22"></property>
<!-- 对象属性-->
<property name="school">
<bean class="com.gyk.ObjInject.School">
<property name="location" value="henan"></property>
<property name="num" value="30000"></property>
</bean>
</property>
<!-- 设置数组属性-->
<property name="hobbies">
<array>
<value>play</value>
<value>sing</value>
<value>ball</value>
</array>
</property>
<!-- 设置 list 属性-->
<property name="schoolList">
<list>
<ref bean="school"></ref>
<ref bean="school2"></ref>
</list>
</property>
<!-- 设置map 属性-->
<property name="stringSchoolMap">
<list>
<map>
<entry>
<key>
<value>map1</value>
</key>
<ref bean="school"></ref>
</entry>
</map>
<map>
<entry>
<key>
<value>map2</value>
</key>
<ref bean="school2"></ref>
</entry>
</map>
</list>
</property>
</bean>
</beans>
package com.gyk.ObjInject;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* ClassName: Student
* Package: com.gyk.depInject
* Description:
*
* @Author Samuel
* @Create 2024/7/24 09:20
* @Version 1.0
*/
public class Student {
private String name;
private int age;
private School school;
private String[] hobbies;
private List<School> schoolList;
private List<Map<String, School>> stringSchoolMap;
public void setStringSchoolMap(List<Map<String, School>> stringSchoolMap) {
this.stringSchoolMap = stringSchoolMap;
}
public void setSchoolList(List<School> schoolList) {
this.schoolList = schoolList;
}
public void setName(String name) {
this.name = name;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
public void setAge(int age) {
this.age = age;
}
public void setSchool(School school) {
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
", hobbies=" + Arrays.toString(hobbies) +
", schoolList=" + schoolList +
", stringSchoolMap=" + stringSchoolMap +
'}';
}
@Test
public void getObj() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ObjInject.xml");
System.out.println(applicationContext.getBean(Student.class));
}
public void setSchoolNum(int num) {
this.school.setNum(num);
}
}
package com.gyk.ObjInject;
/**
* ClassName: School
* Package: com.gyk.depInject
* Description:
*
* @Author Samuel
* @Create 2024/7/24 09:21
* @Version 1.0
*/
public class School {
private String location;
private int num;
public void setLocation(String location) {
this.location = location;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "School{" +
"location='" + location + '\'' +
", num=" + num +
'}';
}
}
2024-07-24 14:09:02 534 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@49872d67
2024-07-24 14:09:02 602 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 3 bean definitions from class path resource [ObjInject.xml]
2024-07-24 14:09:02 615 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'school'
2024-07-24 14:09:02 633 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'school2'
2024-07-24 14:09:02 633 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'student'
Student{name='zs', age=22, school=School{location='henan', num=30000}, hobbies=[play, sing, ball], schoolList=[School{location='henan', num=30000}, School{location='henan', num=30000}], stringSchoolMap=[{map1=School{location='henan', num=30000}}, {map2=School{location='henan', num=30000}}]}
util:list util:map
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<util:list id="list">
<ref bean="school"></ref>
<ref bean="school2"></ref>
</util:list>
<util:list id="list2">
<util:map id="map">
<entry>
<key>
<value>school1</value>
</key>
<ref bean="school"></ref>
</entry>
<entry>
<key>
<value>school2</value>
</key>
<ref bean="school2"></ref>
</entry>
</util:map>
</util:list>
<property name="schoolList" ref="list">
<!-- <list>-->
<!-- <ref bean="school"></ref>-->
<!-- <ref bean="school2"></ref>-->
<!-- </list>-->
</property>
p命名空间
<!-- p命名空间 -->
<bean id="school3" class="com.gyk.ObjInject.School" p:num="11" p:location="ww">
</bean>
<bean id="student2" class="com.gyk.ObjInject.Student" p:age="11" p:name="e11" p:hobbies="{1},{1}"
p:schoolList-ref="list"
p:stringSchoolMap-ref="list2">
</bean>
bean 中读取本地 properties配置属性文件 druid 读取配置属性
先加依赖
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
注意配置 context 命名空间url 和 xsi location url。
@Test
public void getPropertiesInfo() throws SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ObjInject.xml");
DruidDataSource student = (DruidDataSource) applicationContext.getBean(DruidDataSource.class);
System.out.println(student.getUrl());
System.out.println(student.getUsername());
System.out.println(student.getPassword());
// System.out.println(student.getConnection());
System.out.println(student.getCreatedTime());
}
jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC
root
root
Thu Jul 25 11:20:26 CST 2024
bean的作用范围:单实例还是多实例 (默认 singleon 单实例)
取值 | 含义 | 创建对象的时机 |
---|---|---|
singleton(默认) | 在IOC容器中,这个bean的对象始终为单实例 | IOC容器初始化时 |
prototype | 这个bean在IOC容器中有多个实例 | 获取bean时 |
Bean 生命周期
/**
* bean life cycle
* 1. invoke null params controller
* 2. set obj property
* 3. before init
* 4. invoke init method
* 5. after init
* 6. obj init success
* 7. obj destroy
* 8. ioc close
*/
①具体的生命周期过程
bean对象创建(调用无参构造器)
给bean对象设置属性
bean的后置处理器(初始化之前)
bean对象初始化(需在配置bean时指定初始化方法)
bean的后置处理器(初始化之后)
bean对象就绪可以使用
bean对象销毁(需在配置bean时指定销毁方法)
IOC容器关闭
注意其中的initMethod()和destroyMethod(),可以通过配置bean指定为初始化和销毁的方法
<!-- 使用init-method属性指定初始化方法 -->
<!-- 使用destroy-method属性指定销毁方法 -->
<bean class="com.atguigu.spring6.bean.User" scope="prototype"
init-method="initMethod" destroy-method="destroyMethod">
<property name="id" value="1001"></property>
<property name="username" value="admin"></property>
<property name="password" value="123456"></property>
<property name="age" value="23"></property>
</bean>
⑤bean的后置处理器
bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行
public class MyBeanProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("☆☆☆" + beanName + " = " + bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("★★★" + beanName + " = " + bean);
return bean;
}
}
<!-- **⑤bean的后置处理器**-->
<!-- bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行-->
FactoryBean
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。
class MyOBJ {
}
public class FactoryBean implements org.springframework.beans.factory.FactoryBean<MyOBJ> {
@Override
public MyOBJ getObject() throws Exception {
return new MyOBJ();
}
@Override
public Class<?> getObjectType() {
return MyOBJ.class;
}
@Test
public void re() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("FactoryBean.xml");
MyOBJ factoryBean = (MyOBJ) context.getBean("factoryBean"); //只能传id ,FactoryBean.class 会报错
System.out.println(factoryBean);//com.gyk.factory.MyOBJ@7df587ef
}
}
基于xml自动装配
使用bean标签的autowire属性设置自动装配效果
自动装配方式:byType
byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException
<bean id="controller" class="com.gyk.auto_wired.controller.controller" autowire="byType"></bean>
<bean id="service" class="com.gyk.auto_wired.service.service" autowire="byType"></bean>
<bean id="dao" class="com.gyk.auto_wired.dao.dao" autowire="byType"></bean>
public class controller {
public void setServ(service serv) {
this.serv = serv;
}
private service serv;
public void run() {
System.out.println("controller run ");
serv.run();
}
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("autowire.xml");
controller c = (controller) applicationContext.getBean(controller.class);
c.run();
}
}
//
public class service {
private dao d;
public void setD(dao d) {
this.d = d;
}
public void run() {
System.out.println(" service run ");
d.run();
}
}
//
public class dao {
public void run() {
System.out.println(" dao run ");
}
}