Spring项目的创建
-
先创建一个maven 项目
-
添加spring 框架支持(spring- context / spring -beans)
在pom.xml内:<dependencies> <!--注入spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- 注入spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.3.RELEASE</version> </dependency> </dependencies>
-
创建一个启动项并添加main
将对象添加到spring-config.xml的bean中.
-
添加spring 配置文件 (第一次添加bean的时需要进行的操作)
PS: spring配置文件就是要放在resources 目录中, 专门用来存放静态配置文件的文件夹.
<?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对象
-
将Bean对象添加到config文件中
从Spring中取出Bean对象,并使用
第一种方法 : 上下文对象
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
/**
* @Date 2023/4/21 12:21
*/
public class App {
public static void main(String[] args) {
// System.out.println("你好 Spring!");
// // new 一个 spring 上下文对象 指向配置文件spring-config.xml
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
// // 从上下文对象中获取bean s就是Id名 , 然后传出来的是Object对象, 因此要向下转型;
// User user = (User) context.getBean("user");
User user = context.getBean("user",User.class);
user.sayHi("张三");
}
}
-
先获得spring 上下文对象
-
再通过上下文对象提供的方法获取到咱们自己需要使用的Bean对象
-
使用bean对象
第二种方法:Bean工厂:
public static void main(String[] args) {
// 1. 创建工厂
BeanFactory factory =
new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
// 2. 获取bean
User user = (User) factory.getBean("user");
// 3. 使用Bean
user.sayHi("张三");
}
-
获取bean工厂对象
-
获取Bean
-
使用Bean
ApplicationContext 和 BeanFactory的区别:
相同点:
都可以实现从容器中获取Bean, 都提供了getBean
不同点:
-
ApplicationContext 是 BeanFactory的子类
BeanFactory只提供了基础访问Bean的方法,而ApplicationContext除了拥有BeanFactory的所用功能之外, 还提供了更多的方法实现, 比如对国际化的支持,资源访问的支持, 以及事件和传播等方面的支持.
-
从性能方面来说 Beanfactory 是按需加载Bean (懒加载) , AppiactionContext 是饿汉方式, 在创建时会将所有的Bean 都加载起来, 以备以后使用,从而提升了效率, 但是启动时增加了系统资源
如何证明这一观点?
提供两个类,都存储进Spring内部:
查看 创建 ApplicationContext 和 BeanFactory 会不会创造实例对象.
Article类:
User类:
只创建上下文对象查看类是否被初始化了
运行结果如下:
可以看到, 取出Bean对象的情况下, 已经创建好了,构造了所有的Bean实例对象
而BeanFactory结果:
并没有创建一个实例对象
getBean更多用法:
-
使用 bean name 来获取 bean
-
根据 bean type 来获取bean
这样其实是 有一个致命缺陷 : 就是当一个类 id名有多个的时候, 程序会报错:
这里给user类 添加了两个Bean 的id,此时再去获取对象会报错
查看控制台:
就是因为通过User.class 找到了两个不同id的Bean对象
- 根据bean name 和 类型 获取 bean
此时就不会再报错了: