Spring框架基本设置案例_helloSpring

本文通过一个简单的例子介绍了如何使用 Spring 框架实现依赖注入(DI)。包括创建 HelloSpring 类、测试类 Test 和配置文件 applicationContext.xml 的步骤。最终实现了通过 Spring 容器管理对象并进行依赖注入。

1.导包 日志
2.编写applicationContext.xml src下
3.加载配置,创建工程,获得bean

1.导包
这里写图片描述
2.创建类
这里写图片描述
HelloSpring.java

package edu.tsinghua.spring;

public class HelloSpring {
    String message="spring DI!";
    public void say(){
        System.out.println("Hello,"+this.message);
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

Test.java

package edu.tsinghua.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        HelloSpring hs2=new HelloSpring();
        System.out.println(hs2);
        hs2.setMessage("IOC");
        hs2.say();
        System.out.println("-----------");
        //加载配置文件
        BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
        //获得对象 实体
        HelloSpring helloSpring=(HelloSpring)factory.getBean("hs");
        helloSpring.say();
    }

}

*这里写图片描述*
3.新建、编写配置文件
内容如下:
这里写图片描述

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
        "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean name="hs" class="edu.tsinghua.spring.HelloSpring" >
        <property name="message" value="java,你好!"></property>
        <!-- <property name="message">
            <value>NIHAO!</value>
        </property> -->
    </bean>

</beans>

运行后获得如下结果:

Hello,java,你好!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值