创建Spring
先创建一个maven项
在pom.xml中导入jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
</dependencies>
创建业务对象(将对象存入)
package model;
public class UserBean {
public void printName(String name){
System.out.println(name);
}
}
将对象存储到Spring框架中(声明式)
在下图文件中创建.xml文件
<?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">
<beans>
<bean id="user" class="model.UserBean"></bean>
</beans>
</beans>
.xml的名字可以根据自己随意命名。
是将对象存储到Spring框架中,id 是 bean 标识符,用于读取对象,class表示保存到spring当中的对象。可以有多个,但最 bean 中最少要有 id 与 calss
创建一个启动类App,用于测试Spring的核心功能(存储和获取对象)
Spring的使用
先要获取Spring中的上下文,然后通过Spring上下文对象来获取业务对象
import model.UserBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
//获取到Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//从Spring(上下文)中获取到业务对象
UserBean user = (UserBean) context.getBean("user");
//使用业务对象
user.printName("java");
}
}
ApplicationContext 获取Bean(对象)的三种方式 (ApplicationContext 中 后面 .xml 的名字要与自己创建的名字一致)
1、通过Bean的id来获取
UserBean user = (UserBean) context.getBean(“user”);
此种方法需要进行类型转换
2、通过类型获取
UserBean user = context,getBean(UserBean.class);
这个方法无需类型转换,但有个缺点,当多个对象的同一种类型的Bean获取会报错
3、通过id+类型的方式来获取bean
UserBean use = context.getBean(“user”, UserBean.class);
这种方法无需类型转换,多个对象指向一个类的情况也不会报错
还可以通过 BeanFactory 来获取上下文
//获取Spring上下文对象
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
//获取业务对象
UserBean user = beanFactory.getBean("user", UserBean.class);
BeanFactory 与 ApplicationContext 的区别
1、两者来自的jar包不同,
BeanFactory来自sprin.beans.jar下
import org.springframework.beans.factory.BeanFactory;
ApplicationContext 来自spring.cotext.jar下
import org.springframework.context.ApplicationContext;
2、BeanFactory 与 ApplicationContext都是Spring下的顶级接口
ApplicationContext属于BeanFactory的子类,它有BeanFactory的所有功能,还有BeanFactory没有的其他功能。比如:对国际化的支持,支持资源的访问,支持事件的传播等等
3、ApplicationContext会一次性执行所有的bean包,所以它的启动过程较慢,但后续的执行较快, BeanFactory 是用到哪个加载哪个,所以它占用的系统资源更少,启动更快,但后续执行会较慢