spring
asd IOC
l IOC:Inversion(反转) of Control(控制):
正转:木有Spring的时候,我们码代码有以下几步(这几步都是由开发人员控制的)
创建一个类
定义属性和方法(类的两个要素)
New对象(交给SPring管理)
为属性赋值(交给SPring管理)
调用属性
调用方法
加背景色的部分被SPring收回,交给SPring来做;
IOC:其实就是一个容器,放的是叫一个一个的bean;可以通过id快速的找到class对应的对象;(底层也是一个map)
<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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 所有的对象都放到配置文件 只有放到配置文件中,才会被Spring容器所管理 id:唯一 class:包名+类名; 如何通过包名+类名获取对象;Class.forName().newInstance; 其实Spring容器底层也是一个Map,键是Id,值是Class属性对应的Object对象 --> <bean id="demoDynasty" class="com.jinghangzz.spring.pojo.ADemoDynasty"> </bean> </beans>
IOC的主要接口
初始化:
/* IOC的主要接口 */ protected ApplicationContext ac ; /** * 初始化 */ @Before public void init() { /** * 参数:配置文件的路径: * 相对路径是:classpath */ ac = new ClassPathXmlApplicationContext("applicationContext.xml"); this.logger.info("==init==ac:{}",this.ac); }
关闭:
/** * 关闭 */ @After public void close() { this.logger.info("==close=="); /* 判断一下ac是否是ClassPathXmlApplicationContext的一个对象 */ if(this.ac instanceof ClassPathXmlApplicationContext) { /* ac:肯定是ClassPathXmlApplicationContext的一个对象 */ ClassPathXmlApplicationContext cpxac = (ClassPathXmlApplicationContext) this.ac ; cpxac.close(); } }