1.
新建一个工程,
java
基础项目;
2.
将需要使用到的
spring jar
包导入到项目中;
spring-beans-5.2.9.RELEASE.jar
用来定义
spring
的中
bean
对象
( JavaBean )
spring-context-5.2.9.RELEASE.jar
用来创建
applicationContext
对象,从而获取
bean
对象;
spring-core-5.2.9.RELEASE.jar spring
的核心包,用来使用
ioc
spring-expression-5.2.9.RELEASE.jar
用来进行
spring
表达式的定义
spring-jcl-5.2.9.RELEASE.jar
用来进行日志功能的打印
3.
创建
spring
的配置文件,直接在
src
下创建
spring_config.xml
配置文件;复制配置文件中的内
容 从
core.html
中
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
4.
创建一个
Student
类,设置为
JavaBean
对象
5.
补充
spring_config.xml
中内容,在
beans
标签添加
<bean>
标签,设置一个
student
对象
<!--
使用
spring
创建了一个对象
-->
<bean id="student" class="cn.hp.Student"></bean>
6.
使用测试类,获取
spring
容器中的
student
对象
// 1.
加载
spring
的配置文件
spring_config.xml context
就是
spring
的容器
ApplicationContext context = new
ClassPathXmlApplicationContext("spring_config.xml");
// 2.
获取
spring
中的对象
student
Student student = context.getBean("student", Student.class);
System.out.println(student);
spring
的容器
IOC
1.ApplicationContext
常用的容器对象 在加载容器的时候,就将容器中的全部对象进行创建;
三种使用方式:
1
、 通过
ClassPathXmlApplicationContext(
路径
);
通过类路径加载
ClassPath
类路径 可以直接使用
spring_config.xml
作为路径
2
、 通过
FileSystemXmlApplicationContext(
路径
);
FileSystem
通过本地系统路径进行加载文件
C:\\Users\\ck\\Desktop\\
项目
\\spring_demo4_1\\src\\spring_config.xml
3
、 通过
web.xml
自动加载配置文件
2.BeanFactory
旧的容器对象 在加载容器时,不会创建容器中的对象,只有在使用对象时才会创
建; 懒加载
使用
XmlBeanFactory(new ClassPathResource("spring_config.xml"))
方式 加载配
置文件;
spring-bean
spring中bean 指的就是 通过spring配置的对象
在配置文件 xx.xml 中 编写 <bean id="对象名" class="对象的类( 全路径类 带包名 )" >
</bean>
bean的实例化方式
1. spring直接通过new进行创建
配置文件中: <bean id="user1" class="cn.hp.User"></bean>
测试类中: User user1 = (User) context.getBean("user1");
2. 静态工厂的方式 static
创建一个静态的工厂方法,进行创建对昂
3. 实例化工厂的方式
需要将工厂对象先创建出来;然后再通过工厂对象,进行调用创建对象的方法,创建出User对象;
bean的作用域
javase中取值:
singleton:单例模式 整个程序中只会存在一个当前对象 spring中bean默认 作用域值 即
spring中默认对象都为单例
节省内存空间,如果请求用户过多时,可能会造成堵塞;
prototype:原型模式 每次创建的对象都不是同一个; 多例模式
请求速度快,但是占用内存空间;
<bean id="user1" class="cn.hp.User" scope="prototype"></bean>
bean的生命周期
一个对象的创建、使用、销毁的过程;
创建方法: init-method 当对象被创建时,此方法同时被执行,再构造方法之后执行;
销毁方法: destroy-method 当对象被销毁时,此方法同时执行;