• 对Spring Bean的一些思考(对Bean的理解及命名问题)


    Bean简单介绍

    我们知道Spring是一个“大型工厂”,是一个IoC容器。
    那么Bean就是这个工厂的产品,以前我们的对象是由自己 new 出来的,现在,现在是由Spring帮我们制造并且保管,所以说白了。
    Spring是容器,Bean就是容器里装的东西,Bean的概念和对象相似(纠正:当时对Bean理解有些偏差,一个Bean默认为单例模式,就是我一开始误以为理解的一个Bean就是一个实例。而实际上,Bean还有多例模式,一个Bean对应多个实例,本处知识涉及到我刚学的Bean作用域:http://t.csdn.cn/x8UTw)。

    学习过程中有了以下思考:

    新建一个UserController类:
    在这里插入图片描述
    然后在xml注册Bean:
    ![在这里插入图片描述](https://img-blog.csdnimg.cn/cea3082297694c60a97a56b531812453.png在这里插入图片描述

    这里是一个Bean,然后在启动类做以下操作:
    在这里插入图片描述
    创建user 和 user1两个引用,打印二者地址:
    在这里插入图片描述
    这表明两个引用是引用的同一个对象(这个是都知道的)

    那么我们换一种方式
    在这里插入图片描述
    xml注册两个Bean:user1 and user2.
    然后在启动类做以下操作:

    @Controller
    public class App {
        public static void main(String[] args) {
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
            UserController user = applicationContext.getBean("user1",UserController.class);
            UserController user1 = applicationContext.getBean("user2",UserController.class);
            System.out.println(user);
            System.out.println(user1);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    两个引用分别获取user1和user2,再打印
    !](https://img-blog.csdnimg.cn/f031b54959544f6e9d2c55f7b28268d7.png)

    此时二者两个引用引用的对象就不一样了,没有什么神奇的,但是想清楚了这个一下子对bean的理解就更清晰了,回到我们开头对Bean的简单介绍,其实说那么多,Bean其实就是一个个对象,id不同,对象也不同,只不过这个对象是由Spring来创建并托管的(可能说法不太严谨,但理解上应该没错)。

    遇到的Bean的命名问题

    之前遇到的一个问题:
    通过扫描目录注册Bean
    该目录下的类:
    在这里插入图片描述

    在这里插入图片描述
    然后再启动类获取Bean却报错了

    @Controller
    public class App {
        public static void main(String[] args) {
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
            UserController user = applicationContext.getBean("UserController",UserController.class);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    检查了半天,getBean里的名称和类名是对应的,也没有打错呀,但是为什么会报错找不到该bean呢?
    这里就牵扯了Spring扫描目录创建bean的命名规则了
    搜索该方法,是负责创建bean的方法
    在这里插入图片描述
    然后疯狂F4,找到了它的命名规则:
    在这里插入图片描述

    • 如果前两个字母都是大写,则直接使用这个名字
    • 如果非前两个字母都是大写,则将第一个字母转换为小写,然后用转换后的名称命名该Bean

    例如:IsBean会被转换为isBean,而IBean就直接是IBean,不经过转换。
    我们明白了这个之后,对上面报错代码进行验证
    在这里插入图片描述
    将UserController改为userController之后,这次就没有报错
    在这里插入图片描述

  • 相关阅读:
    解析-JsonPath
    第二十章 构建和配置 Nginx (UNIX® Linux macOS)
    MBR40200PT-ASEMI插件肖特基二极管MBR40200PT
    was下log4j设置日志不输出问题
    解决Unity打包时,Android SDK 报错问题
    C语言高校实验室预约登记系统
    tomcat部署jenkins
    关于jQuery_遍历的方法和使用
    协议类型(总结为主,非详细)
    Mac 上 VMvare 虚拟机 Centos 上的 Docker 容器中的文件夹共享到 Mac 实体机
  • 原文地址:https://blog.csdn.net/lzhNox/article/details/127773771