使用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 …即可保存