Spring-1 helloworld

来源:互联网 发布:fifaol3数据库app 编辑:程序博客网 时间:2024/06/06 00:17

毕业设计用了点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即可,而不需要进入程序改动。

0 0