Spring學習(三)
阿新 • • 發佈:2017-12-04
image col prop turn http contex .cn 代碼 con
今天學習的是Spring中一個bean引用另一個bean,需要更改的只是xml配置文件中的代碼,具體代碼如下:
實體類User:
public class User { private String name; private UserService userService; public String getName() { return name; } public void setName(String name) { this.name = name; } public UserService getUserService() {return userService; } public void setUserService(UserService userService) { this.userService = userService; } }
實體類UserService:
public class UserService { private String name; public String getName() { return name; } public void setName(String name) {this.name = name; } }
xml文件配置:
<!-- 在user這個bean中引用userservice這個bean --> <bean id="user" class="com.bdqn.pojo.User"> <property name="name" value="zhangsan" /> <!-- name="userService"表示user類中的userService屬性 --> <!-- ref="userservice"表示引用下面bean中的id="userservice" --> <property name="userService" ref="userservice"/> </bean> <bean id="userservice" class="com.bdqn.pojo.UserService"> <property name="name" value="lisi"></property> </bean>
測試類:
@Test public void show(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) context.getBean("user"); System.out.println(user.getName() + " " + user.getUserService().getName()); }
測試結果:
Spring學習(三)