参考:https://www.yiibai.com/spring/spring-tutorial-for-beginners.html

一、创建项目

1.利用IntelliJ创建Maven项目
2.配置pom.xml,引入Spring


4.0.0

<groupId>com.jh</groupId>
<artifactId>testspring</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <!-- Spring Core -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <!-- Spring Context -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

</dependencies>

二、编写HelloWorld

1.编写接口类HelloWorld

public interface HelloWorld {
    public void sayHello();
}

2.编写实现类HellWorldImplOne

public class HellWorldImplOne implements HelloWorld {
    public void sayHello() {
        System.out.println("hello one");
    }
}

3. 编写依赖类HelloWordDependanceTest

public class HelloWordDependanceTest {
    private HelloWorld helloWorld;


    public void setHelloWorld(HelloWorld helloWorld) {
        this.helloWorld = helloWorld;
    }

    public HelloWorld getHelloWorld() {
        return this.helloWorld;
    }

}

4.编写测试类HelloWorldDependanceMain


public class HelloWorldDependanceMain {
    public static void main(String[] args){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");

        HelloWordDependanceTest service =
                (HelloWordDependanceTest) context.getBean("helloWorldDependanceTest");

        HelloWorld hw= service.getHelloWorld();

        hw.sayHello();

    }
}

5.编写配置文件bean.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="HelloWorldImplOne" class="com.jh.spring.HellWorldImplOne"></bean>

    <bean id="helloWorldDependanceTest" class="com.jh.spring.HelloWordDependanceTest">
                 <property name="helloWorld" ref="HelloWorldImplOne"/>
        </bean>
</beans>

6.运行测试类HelloWorldDependanceMain

posted on 2018-08-05 16:36  grape1211  阅读(133)  评论(0编辑  收藏  举报