1、Spring初学入门教程

来源:互联网 发布:linux vs qt 编辑:程序博客网 时间:2024/06/06 20:14

1、Spring初学入门教程

第一个HelloWorld程序

工程是在以下开发环境下完成的

  • Spring Framework 4.0.4 RELEASE
  • Eclipse MARS 版本
  • maven plugin for eclipse

第一步:创建maven项目

这里写图片描述

第二步:创建目录结构

这里写图片描述

第三步:添加代码

beans.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans                        http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="HelloWorldImpl01"        class="com.main.impl.HelloWorldImpl01"></bean>    <bean id="HelloWorldImpl02"        class="com.main.impl.HelloWorldImpl02"></bean>    <bean id="helloWorldService"        class="com.main.service.HelloWorldService">        <property name="helloWorld" ref="HelloWorldImpl02"/>    </bean></beans>

HelloWorldService.java

package com.main.service;import com.main.model.HelloWorld;public class HelloWorldService {    private HelloWorld helloWorld;    //default constructor    public HelloWorldService(){    }    //HelloWHorld getter    public HelloWorld getHelloWorld() {        return helloWorld;    }    //HelloWorld setter    public void setHelloWorld(HelloWorld helloWorld) {        this.helloWorld = helloWorld;    }}

HelloWorld.java

package com.main.model;public interface HelloWorld {    public void sayHello();}

HelloWorldImpl01.java

package com.main.impl;import com.main.model.HelloWorld;public class HelloWorldImpl01 implements HelloWorld{    public void sayHello() {        System.out.println("HelloWorldImpl-------01");    }}

HelloWorldImpl02.java

package com.main.impl;import com.main.model.HelloWorld;public class HelloWorldImpl02 implements HelloWorld{    public void sayHello() {        System.out.println("HelloWorldImpl------02");    }}

AppTest.java

package com.main.SpringPart01;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.main.model.HelloWorld;import com.main.service.HelloWorldService;public class AppTest {    @Test    public void test(){        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        HelloWorldService service =(HelloWorldService)context.getBean("helloWorldService");        HelloWorld hw= service.getHelloWorld();        hw.sayHello();    }}

第四步:测试运行结果

在以上代码均添加完成后,运用AppTest的junit单元测试运行,可以看到控制台输出结果为下图所示
这里写图片描述

到此,Spring的入门第一个helloworld程序完成

0 0