1. 程式人生 > >Spring 筆記 -03- Spring入門例項- Hello Word!

Spring 筆記 -03- Spring入門例項- Hello Word!

Spring 筆記 -03- Spring入門例項- Hello Word!

步驟:

(1)新建專案,參考 Spring 筆記 -01- Junit 單元測試 中的步驟一
(2)在 main/java 目錄下,新建包 com.spring
(3)在上述包下,新建 HelloWorld.java,編寫程式碼:

package com.spring;

public class HelloWorld {
    public void sayHello (String str){
        System.out.println("HelloWorld " + str);
    }
}

(4)使用 maven 配置 Spring -core 包和 Context 包
開啟:

貼上到 pom.xml 檔案中:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xpwi</groupId>
    <artifactId>firstMaven</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

</project>

(5)在 resource 中新建一個 SpringConfig 檔案,命名為 bean.xml :

(6)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="hello" class="com.spring.HelloWorld"></bean>
</beans>

(7)在 Test/java 目錄中,新建測試類 TestSpring.java 檔案,內容為:

import com.spring.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void testSpring(){

        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        HelloWorld hw = (HelloWorld) ac.getBean("hello");
        String name = JOptionPane.showInputDialog("請輸入一個名字");
        hw.sayHello(name);
    }
}

執行程式!

大家可能遇到錯誤,應該就是使用 JUnit 的問題,請參考:
Spring 筆記 -01- Junit 單元測試

更多文章連結