什么是IOC?什么是DI?
IOC:
控制反转:把创建对象及对象间的关系的维护的权限转交给Spring管理,不是一种技术,而是一种思想,是面对对象编程法则。
案例:
1.引”Jar包“
commons-logging-1.1.1.jar
spring-expression-5.0.2.RELEASE.jar
1spring-core-5.0.2.RELEASE.jar
spring-context-5.0.2.RELEASE.jar
spring-beans-5.0.2.RELEASE.jar
2.配置文件:
配置名xxxx.xml(通常为“applicationContext.xml“)
<?xml version="1.0" encoding="UTF-8"?>applicationContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean标签可以新建对象 -->
<bean id="userSave" class="com.aaa.ioc.User"></bean>
</beans>
3.写个类。
public void showUser(){
System.out.println("IOC第一次测试");
}
4.测试文件。
//1.使用 ApplicationContext 接口,就是在获取 spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.根据Bean的id获得对象
User us=(User)ac.getBean("U");
us.showUser();
DI:
依赖注入,把一个对象依赖另一个对象方式在容器中管理是对象依赖关系,有容器在运行期间决定。
1.引”Jar包
commons-logging-1.1.1.jar
spring-expression-5.0.2.RELEASE.jar
1spring-core-5.0.2.RELEASE.jar
spring-context-5.0.2.RELEASE.jar
spring-beans-5.0.2.RELEASE.jar
2.配置文件:
配置名xxxx.xml(通常为“applicationContext.xml“)
<?xml version="1.0" encoding="UTF-8"?>applicationContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean标签可以新建对象 -->
<bean id="user" class="com.aaa.di.User">
<!--(给对象赋值)注入依赖 -->
<property name="name" value="名字"></property>
<property name="age" value="年龄"></property>
</bean>
</beans>
3.写个类。进行无参构造
4.测试文件。
2.把一个对象注入到另一个对象
创建Dao层
创建Services层
Services层调用Dao层(Dao层)
Services层调用:
private dao层名字 XX;
setter方法
配置文件:
<!-- com.cwy.di -->
<!-- dao层 -->
<bean id="userdao" class="com.cwy.di.dao.UserDaoImpl"></bean>
<!-- service层 -->
<bean id="userservice" class="com.cwy.di.service.UserServiceImpl">
<!-- 注入 value:是普通赋值 ref:注入引用数据类型 对象 -->
<property name="ud" ref="userdao"></property>
</bean>