spring框架源码六、spring ioc xml模式
在我们自定义的ioc中,主要包含两部分, 1、bean信息的定义 bean的类全限定名以及bean之间的依赖关系。 2、BeanFactory 实例化bean对象并维护bean之间的依赖关系。
spring框架的ioc实现中,bean定义信息支持以下几种, 1、xml模式; ioc容器 启动方式: ApplicationContext xmlContext = new ClassPathXmlApplicationContext(); 或 通过ContextLoaderListener监听器加载xml。 2、xml+注解模式; 3、注解模式。 启动方式: ApplicationContext annotationContext = new AnnotationConfigApplicationContext(); 或 通过ContextLoaderListener监听器去加载配置类。
今天我们主要了解下spring ioc容器的纯xml模式。
BeanFactory与ApplicationContext
在spring的ioc实现中,
BeanFactory是spring中的顶级ioc容器接口, ApplicationContext是它的一个子接口, 它多出了国际化支持、加载资源等能力,例如读取xml、java配置类等。
xml模式
pom.xml中引入spring ioc支持
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency>
application-context.xml
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"
default-lazy-init="false">
<bean id="testDao" class="com.duohoob.spring.dao.TestDaoImpl"/>
<bean id="testService" class="com.duohoob.spring.service.TestServiceImpl">
<property name="testDao" ref="testDao"/>
</bean>
</beans>
试一下
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-context.xml");
Object bean = context.getBean("testService");
System.out.println(bean);
}
com.duohoob.spring.service.TestServiceImpl@1990a65e
说明testService实例化完成。
改造TestController
package com.example.duohoob.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.duohoob.service.TestService;
/**
* @author yangwei
*
* @date 2022年10月19日
*/
@RestController
public class TestController {
private static TestService testService;
/**
* 类加载时执行
*/
static {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-context.xml");
testService = (TestService) context.getBean("testService");
((AbstractApplicationContext) context).close();
}
@RequestMapping("/test")
public String test() {
String resp = testService.test();
return resp;
}
}
