一个简单的Spring入门实例

准备工作:

  1.IDE一个,javase版本也可以,最好是javaee版本。推荐eclipse,intellij idea两个优秀的IDE工具

  2.Spring 类库 + commons-logging.jar(如果没有这个jar会报错)。我的spring是使用的最新版本的

  3.新建一个工程.导入lib文件到工程下。本文采用最简单最小白的例子。大神请无视

 

编码工作:

  1.在src文件夹下新建一个Test类,这是此次实例的测试文件,初步代码如下,import部分省略

public class Test {
    public static void main(String[] args) {
        ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml");
        System.out。println(act);
    }
}

      2.ApplicationContext类就是Spring容器类,它是通过bean.xml文件来实例化的

  3.接下来,就在src下面新建一个bean.xml。代码如下。(有IDE自带新建Spring配置文件的可以使用,在右键-New里面应该可以找到)

<?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">

</beans>

  4.然后就可以运行Test类了,输出Spring容器的信息。下面的是我的。

org.springframework.context.support.ClassPathXmlApplicationContext@15d601f: startup date [Sun Nov 10 10:36:32 CST 2013]; root of context hierarchy

  5.上面的只是简单的搭了一个架子。没什么具体作用。现在,就正式写一个小小的实例

  6.在src文件下新建一个Peron类。注意:一定要写一个空参构造函数,否则会报错

public class Person {
    private String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void info(){
        System.out.println("他叫:"+this.getName());
    }
}

  7.此person类具备一个name属性,一对setter,getter,两个构造函数。空参为系统需要,有参数的是习惯,暂时不写也没什么影响。info方法是打印信息

  8.修改bean.xml配置文件:id任意,class就是上面类的名字,property里面的name就是属性的名称,这里是name,而value就是属性的值

<?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="person" class="Person">
        <property name="name" value="tom"></property>
    </bean>

</beans>

  9.修改Test类。这里通过容器类获取到person类并实例化它

public class Test {
    public static void main(String[] args) {
        ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml");
        Person person = act.getBean("person",Person.class);
        person.info();
    }
}

  10.运行Test类,输出:

他叫:tom

  11.Over。一个最简单的例子就这样完成了。

 

总结:因为本人也是刚刚在学,所以Spring框架的作用还不是很理解。

posted @ 2013-11-10 10:50  渲染的青春  阅读(430)  评论(0编辑  收藏  举报