1.创建Maven项目,项目名称springdemo43,如图所示
2.配置Maven,修改项目中的pom.xml文件,修改内容如下
1.0.0 shequ springdemo13 0.0.1-SNAPSHOT 1.7 UTF-8 UTF-8 codelds https://code.lds.org/nexus/content/groups/main-repo javax.annotation jsr250-api 1.0 org.springframework spring-test 4.1.4.RELEASE junit junit 4.10 org.springframework spring-core 4.1.4.RELEASE org.springframework spring-context 4.1.4.RELEASE org.springframework spring-jdbc 4.1.4.RELEASE mysql mysql-connector-java 5.1.34
3.在src/main/java下创建实体Bean Forum,包名(com.mycompany.shequ.bean)如图所示
4.实体Bean Forum的内容如下
package com.mycompany.shequ.bean;public class Forum { private int fid; private String name; private int displayOrder; public int getDisplayOrder() { return displayOrder; } public void setDisplayOrder(int displayOrder) { this.displayOrder = displayOrder; } public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "{fid=>"+this.fid+",name=>"+this.name+",displayOrder=>"+this.displayOrder+"}"; }}
5.在src/main/java下创建实体Bean ForumPost,包名(com.mycompany.shequ.bean)如图所示
6.实体Bean ForumPost的内容如下
package com.mycompany.shequ.bean;public class ForumPost { private int pid; private String name; private Forum forum; public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Forum getForum() { return forum; } public void setForum(Forum forum) { this.forum = forum; }}
7.在src/main/resource下创建bean的配置文件spring-bean.xml,如图所示
8.配置文件spring-bean.xml的内容如下
9.在src/main/resource下创建核心的配置文件applicationContext.xml,如图所示
10.核心的配置文件applicationContext.xml的内容如下
11.在src/test/java下创建测试文件AppTest,包名(com.mycompany.shequ.test)如图所示
12.测试文件AppTest的内容如下
package com.mycompany.shequ.test;import org.junit.Test;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.mycompany.shequ.bean.ForumPost;public class AppTest { @Test public void beanTest(){ ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ForumPost forumPost = (ForumPost) context.getBean("forumpost"); System.out.println(forumPost.getName()); System.out.println(forumPost.getForum()); }}
13.在测试类AppTest的beanTest方法上右键运行,输出结果如图所示