Spring的第一个例子

Spring 的控制翻转IoC,或者依赖注入。在测试类中没有new一个新对象,对象是从xml文件中注入的。

xml文件中的<beans>是一个大容器,里面的<bean>就是容器里面的内容,这些内容是一个一个的实例对象。

我们把对象创建在了xml文件中,所以就不用再在Java中创建对象了,当我们使用这些对象的时候,就从xml的bean注入即可。

1.创建类

package com.wangcf;

public class HelloWorld {
    private String name;
    public void sayHello(){
        System.out.println("Hello World"+name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2.创建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" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    >
    <!-- 注册一个Hello World,实例名称为HelloWorld -->
    <bean name="helloworld" class="com.wangcf.HelloWorld">
        <property name="name">
            <value>小明</value>
        </property>
    </bean>
</beans>

3.创建测试类

package com.wangcf;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloTest {

    @Test
    public void testSayHello() {
        //创建Spring 容器
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        //从容器中得到一个bean,也就是一个实例对象
        HelloWorld hello=(HelloWorld)context.getBean("helloworld");
        hello.sayHello();
    }

}

4.输出结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值