个人对依赖和注入的理解
依赖:一个bean的内部含有其他bean,这个bean依赖于内部的bean运行
注入:对一个bean内部的bean进行注入
1.set方法注入
实现类源码:
public class UserMapperImpl implements UserMapper {
@Override
public void save() {
System.out.println("user mapper save()...");
}
}
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
@Override
public void save() {
System.out.println("user service impl save()...");
userMapper.save();
}
//需要对进行依赖注入的类中提供被注入对象对应的set方法
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
}
xml配置:
<!--
property中的name属性为UserServiceImpl中setUserMapper方法去掉set字母的小驼峰命名
ref属性为当前xml配置文件中bean的id
-->
<bean id="userMapper" class="com.nf.mapper.impl.UserMapperImpl"/>
<bean id="userService" class="com.nf.service.impl.UserServiceImpl">
<property name="userMapper" ref="userMapper"/>
</bean>
2.构造器注入
xml配置:
<bean id="userMapper" class="com.nf.mapper.impl.UserMapperImpl"/>
<!--
<constructor-arg/>:表示使用构造器进行注入
name属性为构造器参数上的名称
ref属性为xml配置文件中bean的id
-->
<bean id="userService" class="com.nf.service.impl.UserServiceImpl">
<constructor-arg name="userMapper" ref="userMapper"/>
</bean>
测试类:
public class App {
public static void main(String[] args) {
//加载配置文件,获取上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();
}
}
(如有错误,请指正)