博客
关于我
spring(5)——通过import标签整合多个beans
阅读量:322 次
发布时间:2019-03-04

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

1.创建applicationContext.xml文件和beans2.xml文件

  1. beans2.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">    <!-- 使用spring来创建对象,在spring这些都称为bean -->    <bean id="hello" class="com.lixv.entity.Hello">        <constructor-arg index="0" value="xxxxxxxxxxxx"/>    </bean>    <bean id="helloSpring" class="com.lixv.entity.HelloSpring" name="helloSpringNew1,helloSpringNew2">        <property name="springStr" value="springstr"/>        <property name="hello" ref="hello"/>    </bean>    <alias name="helloSpring" alias="helloSpringNew"/></beans>
  1. applicationContext.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">   <import resource="beans2.xml"/>   <import resource="beans.xml"/></beans>
  1. import可以将其他beans中的bean添加过来
  2. 当导入多个beans,其中有相同的bean(对象)时,spring会自动将其合并
  3. 当import多个beans,其中的bean拥有相同的id,但是对象属性不同时。通过getBean("helloSpringNew1")获取这个id会得到最后import的beans中的bean(当id相同时:后import的会覆盖先import的)

2.测试代码

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("applicationContext.xml");        HelloSpring hellospring1 = (HelloSpring) context.getBean("helloSpringNew1");        System.out.println(hellospring1);    }}

3.运行结果

在这里插入图片描述

转载地址:http://voeq.baihongyu.com/

你可能感兴趣的文章
【Oozie】(三)Oozie 使用实战教学,带你快速上手!
查看>>
师兄面试遇到这条 SQL 数据分析题,差点含泪而归!
查看>>
C语言的数值溢出问题(上)
查看>>
BottomNavigationView控件item多于3个时文字不显示
查看>>
函数指针的典型应用-计算函数的定积分(矩形法思想)
查看>>
8051单片机(STC89C52)以定时器中断模式实现两倒计时器异步计时
查看>>
用 wxPython 打印你的 App
查看>>
vue项目通过vue.config.js配置文件进行proxy反向代理跨域
查看>>
Linux下安装MySql过程
查看>>
android:使用audiotrack 类播放wav文件
查看>>
vue通过better-scroll 封装自定义的下拉刷新组件
查看>>
android解决:使用多线程和Handler同步更新UI
查看>>
Element UI 中动态路由的分析及实现
查看>>
使用springMVC配置视图管理器后找不到指定的页面
查看>>
杭电 2007 平方和与立方和(输入数据的大小顺序并不能默认)
查看>>
十大排序算法之三:插入排序(Python)
查看>>
利用递归实现二叉树的前中后序遍历(Python)
查看>>
冒泡排序又来啦(C/C++版本)
查看>>
python负数存储
查看>>
合并两个有序数组
查看>>