Spring-1 helloworld

毕业设计用了点spring的皮毛,几个月过去又给忘记了,现在想重新捡起来,想翻翻记录发现一条也没有,很后悔。
现在算是重新来一遍吧,希望自己可以坚持下去。

本来是想学学springMVC,一看教程,springMVC基于Spring, 如果Spring啥也不知道,估计也学不下去,于是又翻出来佟刚的视频看看。

工程结构:
这里写图片描述

1.建立一个普通java project
2.工程目录下建lib,放入jar(下面四个是必须的),并 build path
这里写图片描述
3.创建包com.csu.hello
4.在hello包下创建类:helloworld:

package com.csu.hello;

public class helloworld {
    String name;

    public helloworld()
    {
        System.out.println("constructor......");
    }

    public void setName(String name) {
        System.out.println("set name....."+name);
        this.name=name;
    }

    public void greet() {
        System.out.println("hello:"+this.name);
    }
}

5.在hello包下创建Main类:

package com.csu.hello;

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

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        1.helloworld实例
        helloworld h1=new helloworld();
        2.设置属性值
        h1.setName("Jerry");
        3.调用实例方法
        h1.greet();
    }

}

以上步骤还跟spring没有一毛钱关系,一切都是传统做法,现在,用上IOC容器来达到一样的效果:
首先,在src下新建一个applicationContext.xml来写bean配置:

<?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 -->
<bean id="helloWorld" class="com.csu.hello.helloworld">
    <!--配置 属性-->
    <property name="name" value="Jerry"></property>
</bean>

</beans>

然后改了Main:

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*1.helloworld实例
        helloworld h1=new helloworld();
        2.设置属性值
        h1.setName("Jerry");
        3.调用实例方法
        h1.greet();*/
        //1.获取IOC容器
        AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.获取bean实例
        helloworld myHello=(helloworld) ctx.getBean("helloWorld");
        //3.调用实例方法
        myHello.greet();
    }

运行结果一直,控制台打印出:hello Jerry
可以看到,用上Spring 的 IOC之后,我们想获得一个完整bean实例,不用自己new了,也不用自己调用set方法来设置属性,只要我们在xml里面把模子()做好之后,获取IOC容器,调用getBean(“beanid”)方法即可。

这样做的好处,首先,是便于管理所有实例,其次,如果修改某个实例的属性,只需要改xml 的property即可,而不需要进入程序改动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值