1. 程式人生 > 實用技巧 >IDEA+Maven+Spring5.X專案建立

IDEA+Maven+Spring5.X專案建立

建立maven

新增依賴

pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency
> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <
artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> </dependencies>

新增配置檔案applicationContext.xml

在src/main/resources下建立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="video" class="net.cybclass.sp.domain.Video"> <property name="id" value="9"></property> <property name="title" value="Spring5.X課程"></property> </bean> </beans>

bean標籤

  • id屬性:指定Bean的名稱,在Bean被別的類依賴時使用
  • name屬性:用於指定Bean的別名,如果沒有id,也可以用name
  • class屬性:用於指定Bean的來源,要建立Bean的class類,需要全限定名

建立Video.java

package net.cybclass.sp.domain;

public class Video {
    private int id;
    private String title;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

建立app.java

package net.cybclass.sp;

import net.cybclass.sp.domain.Video;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class app {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        Video video=(Video) applicationContext.getBean("video");
        System.out.println(video.getTitle());
    }
}

完整專案結構

執行