Maven創建Spring項目


使用idea, 通過maven新建一個spring項目

  1. File --> new --> project -->maven

  2. 設置項目名稱,位置,包名等

  3. 引入spring framework
    3.1 到mvnrepository.com 搜索spring context

    3.2 復制引入maven的代碼

    3.3 將復制到代碼粘貼到項目的pom文件中

    <?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.stark</groupId>
        <artifactId>Test</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.3.16</version>
            </dependency>
    
        </dependencies>
    
    </project>
    

    3.4 點擊 load maven change , 加載引入的spring框架

  4. 在項目中新建一個Person類

    package com.stark;
    public class Person {
    }
    
  5. 新建spring項目的配置文件applicationContext.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="person" class="com.stark.Person"/> <!-- 自己輸入這一行-->
    </beans>
    
  6. 新建Test類

    package com.stark;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class Test {
        public static void main(String[] args) {
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            Object person = ctx.getBean("person");
            System.out.println(person);
        }
    }
    
  7. 運行main方法. 控制台就會輸出com.stark.Person@1ed4004b . 這就建好了一個Spring項目

    com.stark.Person@1ed4004b
    
    Process finished with exit code 0
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM