如何创建spring项目

这篇博客详细介绍了如何在IntelliJ IDEA中创建一个Spring项目,包括设置项目结构、编写Book和Author类、配置XML文件以及创建Main方法进行运行。通过这个过程,读者可以学习到Spring项目的创建步骤以及如何通过XML配置文件管理和实例化Bean。
摘要由CSDN通过智能技术生成

使用IDEA创建项目

创建spring项目

在这里插入图片描述
等待下载完成,lib目录下应该有17个jar包


在这里插入图片描述
创建目录结构(其中one是模块)


在这里插入图片描述
在src下创建xml文件,xml文件如图所示
在这里插入图片描述


注意:创建好项目后,要检查JDK版本、maven路径等,查看是否正确


在one目录下创建:book类,声明属性创建Author作者类,声明作者的属性

package com.boke.one;

public class Book {
	//声明书的属性:书名、作者
	private String bookName;
	private String author;
	//添加get、set方法     (alt+insert-->getter and setter,选择全部属性--> ok)
	public String getBookName () {
		return this.bookName;
	}

	public void setBookName (String bookName) {
		this.bookName = bookName;
	}

	public String getAuthor () {
		return author;
	}

	public void setAuthor (String author) {
		this.author = author;
	}
	//实例方法,输出属性
	public void bookInfo(){
		System.out.println("书名:"+this.bookName+"\n"+"作者:"+this.author);
	}

}

继续创建:作者类

package com.boke.one;

public class Author {
	//声明作者的属性
	private String name;
	private int age;

	public String getName () {
		return name;
	}

	public void setName (String name) {
		this.name = name;
	}

	public int getAge () {
		return age;
	}

	public void setAge (int age) {
		this.age = age;
	}
	//实例方法,输出属性
	public void authorInfo () {
		System.out.println("西游记的作者是:"+this.name+"\n"+"年龄是:"+this.age);
	}
}

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">
    <!--xml支持html注释-->

    <!--one模块-->
    <bean id="book" class="com.boke.one.Book">
        <!--为属性设值-->
        <property name="bookName" value="《西游记》"/>
        <property name="author" value="吴承恩"/>
    </bean>
    <bean id="author" class="com.boke.one.Author">
        <!--为属性设值-->
        <property name="name" value="吴承恩"/>
        <property name="age" value="34"/>
    </bean>
</beans>

最后编写Main方法

package com.boke.one;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	public static void main (String[] args) {
		//将xml与类联系起来
		ApplicationContext context = new  ClassPathXmlApplicationContext("Beans.xml");

		Book book = context.getBean("book",Book.class);//“book"要与xml中的id相同
		book.getBookName();//直接调用无值,因此创建实例方法调用,应省略此行代码
		book.bookInfo();//调用实例方法

		Author author = context.getBean("author",Author.class);//"author"要与xml中的id相同
		//author.getName(); //已省略,不应这样写
		author.authorInfo();//调用实例方法
	}
}


创建spring项目完成


尝试运行:找到main方法,点击运行
在这里插入图片描述
结果如下:
在这里插入图片描述


最后注意,如果需要为项目保存配置,点击save …即可保存
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值