1.创建Maven项目,项目名称springdemo17,如图所示
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 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; 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; } }
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 ForumPost() { super(); } public ForumPost(Forum forum) { super(); this.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; } }
7.在src/main/resources下创建Bean配置文件,配置文件名称spring-bean.xml,如图所示
8.spring-bean.xml文件的内容如下
9.在src/test/java下创建测试类ForumPostTest,包名(com.mycompany.shequ.bean),如图所示
10.测试类ForumPostTest的内容如下
package com.mycompany.shequ.bean;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ForumPostTest { /** * spring 的自动装配Beans,通过构造函数参数的数据类型按属性自动装配Bean */ @Test public void constructorTest(){ ApplicationContext context = new ClassPathXmlApplicationContext("/bean/spring-bean.xml"); ForumPost forumPost = (ForumPost) context.getBean("forumpost"); System.out.println(forumPost.getForum().getName()); }}
11.在测试类ForumPostTest的byTypeTest方法上右键运行,输出结果如图所示