重温Spring框架(二、Spring Bean的装备模式之二:Bean的配置)

40 篇文章 0 订阅

1、applicationContext.xml完整的配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--   bean常用属性-->
    <bean id="bean1" class="com.ssm.Bean1" name="" scope="" />

    <!--    bean常用子元素-->
    <bean id="bean2" class="com.ssm.Bean2" name="" scope="">
        <constructor-arg name="" type="" ref="" value="">
            <list></list>
            <set></set>
            <map>
                <entry></entry>
            </map>
        </constructor-arg>

        <property name="" value="" ref="" >
            <list></list>
            <set></set>
            <map>
                <entry></entry>
            </map>
        </property>

    </bean>

</beans>

2、singleton(单实例)作用域和prototype(原型模式)的例子比较:

2-1:HelloSpring类的代码:

package com.ssm;

public class HelloSpring{
    private String userName;

    public void show(){
        System.out.println(userName + "欢迎学习使用Spring框架");
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

2-2:applicationContext.xml的配置:

    <!--   配置创建HelloSpring的实例-->
<!--    <bean id="helloSpring" class="com.ssm.HelloSpring" scope="singleton">   &lt;!&ndash; new出来的实例相等 &ndash;&gt;-->
    <bean id="helloSpring" class="com.ssm.HelloSpring" scope="prototype">   <!--    new出来的实例不相等  -->
        <property name="userName" value="张三" />
    </bean>

2-3:TestHelloSpring类的代码:

package com.ssm;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloSpring {

    public static void main(String[] args) {

        // 初始化Spring容器,加载applicationContext.xml配置
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        // 通过容器获取配置中的helloSpring的实例
        HelloSpring helloSpring1 = (HelloSpring) ctx.getBean("helloSpring");
        HelloSpring helloSpring2 = (HelloSpring) ctx.getBean("helloSpring");

        // 判断取得实例值是否相等
        System.out.println(helloSpring1 == helloSpring2);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值