spring(4)——给beans中的bean对象取别名的两种方式,alias标签和bean的name属性
发布日期:2021-05-07 02:55:46 浏览次数:27 分类:精选文章

本文共 1158 字,大约阅读时间需要 3 分钟。

1.alias标签

package com.lixv.dao;import com.lixv.entity.Hello;import com.lixv.entity.HelloSpring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestSpring {       public static void main(String[] args) {           ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        HelloSpring hellospring1 = (HelloSpring) context.getBean("helloSpringNew");        System.out.println(hellospring1);    }}
  1. 这样就可以通过helloSpringNew来获取helloSpring这个对象
  2. 仍然可以通过helloSpring来获取helloSpring这个对象
    在这里插入图片描述

2.通过bean的name属性来取别名

public class TestSpring {       public static void main(String[] args) {           ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        HelloSpring hellospring1 = (HelloSpring) context.getBean("helloSpringNew1");        System.out.println(hellospring1);    }}
  1. 可以通过helloSpringNew1或者helloSpringNew2来获取helloSpring对象。
  2. bean的name属性可以一次性设置多个别名,用逗号分号空格分开皆可。
  3. 仍然可以通过alias设置的别名和bean的id来获取这个对象
    在这里插入图片描述
上一篇:spring(5)——通过import标签整合多个beans
下一篇:spring(2)——通过配置文件使用类,实现控制反转,实现不同的操作只需要在xml文件中进行修改

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年04月14日 21时21分12秒