手把手入門,運行第一個spring程序(idea版)

新建Maven項目

這裏用了maven,得有點maven基礎,會導入依賴就行,選擇maven項目,直接下一步。

隨便取個帥氣的項目名,完成。

導入依賴

編輯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>org.example</groupId>
    <artifactId>hello</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- ioc需要的依賴 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
    </dependencies>
</project>

編寫代碼

首先,標準的maven項目結構:

org.example.bean.Hello

package org.example.bean;

/**
 * @author MaoLongLong
 */
public class Hello {

    public Hello() {
        System.out.println("對象被創建");
    }

    public void sayHello() {
        System.out.println("Hello World!");
    }
}

main/resources下新建一個配置文件applicationContext.xml

把Hello注入到spring容器中

<?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 class="org.example.bean.Hello" id="hello"/>
</beans>

如果看不慣頂上的提示,可以配置一下項目結構,然後提示就消失了。



最後在Main中調用

package org.example;

import org.example.bean.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Objects;

/**
 * @author MaoLongLong
 */
public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Hello hello1 = (Hello) ctx.getBean("hello");
        hello1.sayHello();
        Hello hello2 = ctx.getBean("hello", Hello.class);
        hello2.sayHello();
        System.out.println(Objects.equals(hello1, hello2));
    }
}

輸出結果:

對象被創建
Hello World!
Hello World!
true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章