对象依赖关系
DI: 依赖注入
- 通过构造
- 通过Set方法对属性进行注入
- 通过p命名空间
- 自动装配
- 注解
使用Set方法对属性进行注入
以常见的三层架构Action , Service, Dao 示例
项目结构:
1.png
applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Action -->
<bean id="UserAction" class="com.iotek.second.UserAction">
<property name="UserService" ref="UserService"></property>
</bean>
<!-- Service -->
<bean id="UserService" class="com.iotek.second.UserService">
<property name="UserDao" ref="UserDao"></property>
</bean>
<!-- Dao -->
<bean id="UserDao" class="com.iotek.second.UserDao"></bean>
</beans>
UserAction.java:
package com.iotek.second;
public class UserAction {
UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void addUser() {
userService.save();
}
}
UserService.java文件:
package com.iotek.second;
public class UserService {
UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void save() {
userDao.save();
}
}
UserDao.java文件:
package com.iotek.second;
public class UserDao {
public void save() {
System.out.println("保存数据库成功");
}
}
UserTest.java文件:
package com.iotek.second;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserAction userAction = (UserAction) applicationContext.getBean("UserAction");
userAction.addUser();
}
}
当然,配置xml文件也可以使用内部bean的方式,如下
<!-- 内部bean -->
<bean id="UserAction2" class="com.iotek.second.UserAction">
<property name="UserService">
<bean class="com.iotek.second.UserService">
<property name="UserDao">
<bean class="com.iotek.second.UserDao"></bean>
</property>
</bean>
</property>
</bean>
网友评论