今天学习的是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()); }
测试结果:
时间: 2024-10-18 03:31:14