1、Spring 容器加载的3种方式

  1. public class ServiceTest {
  2. public static void main(String[] args) {
  3. //Spring容器加载有3种方式
  4. //第一种:ClassPathXmlApplicationContext ClassPath类路径加载,指的就是classes路径
  5. //第一种:最常用,spring的配置文件路径以后就直接放在src
  6. ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  7. //第二种方式:文件系统路径获得配置文件【绝对路径】
  8. //ApplicationContext context = new FileSystemXmlApplicationContext("C:\\Users\\Desktop\\IDEAWorkspace\\spring-01\\src\\com\\rookie\\beans.xml");
  9. //第三种方式:使用BeanFactory(了解)
  10. //String path = "C:\\Users\\Desktop\\IDEAWorkspace\\spring-01\\src\\com\\rookie\\beans.xml";
  11. //BeanFactory factory = new XmlBeanFactory(new FileSystemResource(path));
  12. //IUserService user = (IUserService) factory.getBean("userService");
  13. //user.add();
  14. IUserService user = (IUserService) context.getBean("userService");
  15. user.add();
  16. }
  17. }

Spring内部创建对象的原理

a.解析xml文件,获取类名,id,属性等。

b.通过反射,用类型创建对象。

c.给创建的对象赋值。

2、BeanFactory 和 ApplicationContext对比

BeanFactory 采取延迟加载,第一次 getBean 时才会初始化 Bean。

ApplicationContext 是即时加载,对 BeanFactory 扩展,提供了更多功能。

  • 案例演示(在第一次的代码基础上)

    1. public class UserServiceImpl implements UserService {
    2. private String name;
    3. public void setName(String name) {
    4. this.name = name;
    5. }
    6. @Override
    7. public void add() {
    8. System.out.println("创建用户...." + name);
    9. }
    10. public UserServiceImpl(){
    11. System.out.println("UserServiceImpl() 调用了");
    12. }
    13. }
    1. public class ServiceTest {
    2. public static void main(String[] args) {
    3. //1.加载beans.xml 这个spring的配置文件,内部就会创建对象
    4. ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    5. }
    6. }

    控制台打印日志:UserServiceImpl( ) 调用了

    1. public class ServiceTest {
    2. public static void main(String[] args) {
    3. String path = "C:\\Users\\Desktop\\IDEAWorkspace\\spring-01\\src\\com\\rookie\\beans.xml";
    4. BeanFactory factory = new XmlBeanFactory(new FileSystemResource(path));
    5. // 要使调用空参构造可以放开这段代码即可
    6. // IUserService user = (IUserService) factory.getBean("userService");
    7. }
    8. }

    控制台没有打印日志,说明空参构造没有被调用。

    放开上面注释的代码,即可调用空参构造,控制台打印日志:UserServiceImpl( ) 调用了。

2、Spring 容器装配 bean 的 3 种方式

所谓的装配bean就是在xml写一个bean标签。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!--装配bean的三种方式,所谓的装配bean就是在xml写一个bean标签-->
  7. <!-- 第一种方式: new 实现类-->
  8. <bean id="userService1" class="com.example.demo.service.impl.UserServiceImpl">
  9. <property name="name" value="zhangsan"></property>
  10. </bean>
  11. <!-- 第二种方式:通过静态工厂方法 -->
  12. <bean id="userService2" class="com.example.demo.service.UserServiceFactory" factory-method="createUserService"/>
  13. <!--第三种方式:通过实例工厂方法 -->
  14. <bean id="factory2" class="com.example.demo.service.UserServiceFactory2"/>
  15. <bean id="userService3" factory-bean="factory2" factory-method="createUserService"/>
  16. </beans>

测试上面哪种 bean 装配方式,需要注释掉其他 bean装配方式。

第一种上次已经讲过,现在只讲第二、三种案例。

  1. public class UserServiceFactory {
  2. public static UserService createUserService() {
  3. return new UserServiceImpl();
  4. }
  5. }
  6. =========================================================================================
  7. public class UserServiceFactory2 {
  8. public UserService createUserService() {
  9. return new UserServiceImpl();
  10. }
  11. }

执行测试函数

  1. public class ServiceTest {
  2. public static void main(String[] args) {
  3. //new 对象
  4. ApplicationContext context1 = new ClassPathXmlApplicationContext("beans.xml");
  5. UserService userService1 = (UserService) context1.getBean("userService1");
  6. userService1.add();
  7. //静态工厂
  8. ApplicationContext context2 = new ClassPathXmlApplicationContext("beans.xml");
  9. UserService userService2 = (UserService) context2.getBean("userService2");
  10. userService2.add();
  11. //实例工厂
  12. ApplicationContext context3 = new ClassPathXmlApplicationContext("beans.xml");
  13. UserService userService3 = (UserService) context3.getBean("userService3");
  14. userService3.add();
  15. }
  16. }

感兴趣的可以自己看执行结果。三种结果都证明 bean 被 Spring 容器管理实例化了。

3、bean的作用域(掌握 singleton、prototype)

类别 说明
singleton 在Spring IoC容器中仅存在一个Bean实例,Bean以单例方式存在,默认值
prototype 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时 ,相当于执行new XxxBean()
request 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境
session 同一个HTTP Session 共享一个Bean,不同Session使用不同Bean,仅适用于WebApplicationContext 环境
globalSession 一般用于Portlet应用环境,该作用域仅适用于WebApplicationContext 环境

案例代码演示

  1. bean.xml 文件
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  7. <bean id="userService1" class="com.example.demo.service.impl.UserServiceImpl" scope="prototype">
  8. </bean>
  9. </beans>
  1. public class ServiceTest {
  2. public static void main(String[] args) {
  3. ApplicationContext context1 = new ClassPathXmlApplicationContext("beans.xml");
  4. UserService userService1 = (UserService) context1.getBean("userService1");
  5. UserService userService2 = (UserService) context1.getBean("userService1");
  6. System.out.println(userService1);
  7. System.out.println(userService2);
  8. }
  9. }

控制台信息如下:

com.example.demo.service.impl.UserServiceImpl@2a556333

com.example.demo.service.impl.UserServiceImpl@7d70d1b1

如果去掉 bean.xml 文件的 scope="prototype",打印信息如下:

com.example.demo.service.impl.UserServiceImpl@7a187f14

com.example.demo.service.impl.UserServiceImpl@7a187f14

所以Spring IoC容器Bean以单例方式默认存在!!配置的话根据自己需要配置单例或者多例

Spring 讲解(二 )的更多相关文章

  1. Redis实战之征服 Redis + Jedis + Spring (二)

    不得不说,用哈希操作来存对象,有点自讨苦吃! 不过,既然吃了苦,也做个记录,也许以后API升级后,能好用些呢?! 或许,是我的理解不对,没有真正的理解哈希表. 相关链接: Redis实战 Redis实 ...

  2. Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控

    Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...

  3. spring batch(二):核心部分(1):配置Spring batch

    spring batch(二):核心部分(1):配置Spring batch 博客分类: Spring 经验 java   chapter 3.Batch configuration 1.spring ...

  4. Spring Boot 二十个注解

    Spring Boot 二十个注解 占据无力拥有的东西是一种悲哀. Cold on the outside passionate on the insede. 背景:Spring Boot 注解的强大 ...

  5. 风炫安全web安全学习第三十七节课 15种上传漏洞讲解(二)

    风炫安全web安全学习第三十七节课 15种上传漏洞讲解(二) 05后缀名黑名单校验之上传.htaccess绕过 还是使用黑名单,禁止上传所有web容器能解析的脚本文件的后缀 $is_upload = ...

  6. Spring Boot(二):数据库操作

    本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式来访问数据库,第一种是JdbcTemplate,第二种是JPA,第三种是Mybatis.之前已经提到过,本系列会以一个博客系统 ...

  7. spring学习(二) ———— AOP之AspectJ框架的使用

    前面讲解了spring的特性之一,IOC(控制反转),因为有了IOC,所以我们都不需要自己new对象了,想要什么,spring就给什么.而今天要学习spring的第二个重点,AOP.一篇讲解不完,所以 ...

  8. Spring(二十):Spring AOP(四):基于配置文件的方式来配置 AOP

    基于配置文件的方式来配置 AOP 前边三个章节<Spring(十七):Spring AOP(一):简介>.<Spring(十八):Spring AOP(二):通知(前置.后置.返回. ...

  9. Spring系列(二):Spring IoC/DI的理解

    这几天重新学习了一下Spring,在网上找了相关的ppt来看,当看到Spring IoC这一章节的时候,先大致浏览了一下内容,有将近50页的内容,内心窃喜~QAQ~,看完这些内容能够对IoC有更深层次 ...

随机推荐

  1. js百度地图API创建弧线并修改弧线的弧度

    去百度API官网下载CurveLine.min.js,注意复制下来的Js前面的行号要删除. // 百度地图API功能 var map = new BMap.Map("container&qu ...

  2. Android SDK的下载与安装*(PC版)

    Android SDK的下载与安装   一.Android SDK简介下载地址:https://www.androiddevtools.cn/ 将下载后的安装包解压到相应的目录下,如下图: 三.安装A ...

  3. Redis5离线安装

    1. 直接上redis官网安装包, 然后上传服务器 https://redis.io/download 2. 解压 tar -zxvf redis-5.0.6.tar.gz 3. 进入redis根目标 ...

  4. flutter图片组件

    在flutter中,image组件有很多构造函数,常用的包括Image.asset(本地图片)和Image.network(远程图片). 常用属性 不管是显示本地图片还是远程图片,image组件都包含 ...

  5. 112、TensorFlow初始化变量

    # 创建一个变量 # 最简单创建一个变量的方法就是调用 tf.get_variable function import tensorflow as tf # 下面创建了一个三维的张量大小是 [1,2, ...

  6. appium常见问题07_appium输入中文无效

    前几天在appium android自动化测试过程中,使用send_keys()输入中文,发现只能输入字母和数字,输入中文无反应. 大家是否同样遇到过该问题,当大家同样遇到该问题时,在配置参数desi ...

  7. [题解]Shorten IPv6 Address-模拟(2019牛客多校第六场B题)

    题目链接:https://ac.nowcoder.com/acm/contest/886/B 题意: 您将获得一个IPv6地址,该地址是128位二进制字符串.请根据以下规则确定其最短的表示: 以十六进 ...

  8. UVA12589_Learning Vector

    大致题意: 有n个向量要你选k个,把这k个向量连起来,画出来的与x轴围成的面积最大 思路: 这个是斜率dp,让斜率大的排在前面,记忆化搜索的时候要加入一个当前高的信息,因为这个向量形成面积不仅和斜率有 ...

  9. str方法

    'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', ' ...

  10. luogu P4183 Cow at Large P (暴力吊打点分治)(内有时间复杂度证明)

    题面 贝茜被农民们逼进了一个偏僻的农场.农场可视为一棵有N个结点的树,结点分别编号为 1,2,-,N .每个叶子结点都是出入口.开始时,每个出入口都可以放一个农民(也可以不放).每个时刻,贝茜和农民都 ...