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());
    }
}

完整项目结构

运行

原文地址:https://www.cnblogs.com/chenyanbin/p/13302036.html