Spring第一餐

项目结构图

这里写图片描述

代码

HelloWorld.java

package org.spring.model;

public class HelloWorld {
    public String sayHello(){
        return "hello world";
    }
}

beans.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">

    <bean id="helloWorld" class="org.spring.model.HelloWorld" scope="prototype"/>
</beans>

Test.java

package org.spring.test;

import org.spring.model.HelloWorld;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    //创建spring的工厂
    private BeanFactory factory=new ClassPathXmlApplicationContext("xml/beans.xml");

    @org.junit.Test
    public void testHello() {
        //通过工厂获取对象(下面getBean方法中的参数是beans.xml文件中bean的id)
        //HelloWorld hello=(HelloWorld) factory.getBean("helloWorld");      //不指定返回对象的类型(默认返回object类型,需要进行强制转换)
        HelloWorld hello=factory.getBean("helloWorld", HelloWorld.class);   //返回指定类型的对象
        System.out.println(hello.sayHello());
        HelloWorld hello2=factory.getBean("helloWorld", HelloWorld.class);
        System.out.println(hello==hello2);      //如果在bean中没有配置scope,默认是singleton(单独,单例),返回true,当把bean中的scope设置为prototype(原型,多例)时返回false
    }
}

运行结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值