深入Spring源码专题(7)

117 阅读1分钟

这是我参与2022首次更文挑战的第13天,活动详情查看2022首次更文挑战

ApplicationContext

在Spring中,ApplicationContext接口是BeanFactory的一个扩展,除了DI服务,ApplicationContext还提供了其他服务,如事务和AOP服务、国际化的消息源以及应用程序事件处理等。在开发基于Spring的应用程序时,建议通过ApplicationContext接口与Spring进行交互。Spring通过手动编码(通过手动实例化并加载适当的配置)或在Web容器环境中通过ContextLoaderListener来支持ApplicationContext的启动。

配置ApplicationContext
设置Spring配置选项

对于XML配置,需要声明应用程序中需要的由Spring提供的名称空间基础信息。该例仅声明了用于定义Spring Bean的Bean的名称空间。将配置文件appcontextxml.xml用于XML样式的配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmls="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

除了bean,Spring还为不同目的提供了大量其他名称空间,比如针对ApplicationContext配置的上下文,用于AOP支持的aop以及用于事务支持的tx。

在应用程序中使用Spring的注解支持,需要在XML配置中声明以下配置的标记,可将此配置文件称为app-context-annotation.xml,用于支持带有注解的XML配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmls="http://www.springframework.org/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:c="http://www.springframework.org/schema/c"
	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">
<context:component-scan base-package="com.ozx.annotation">
</beans>

context:component-scan标记让Spring扫描代码,从而找到使用@Component、@Controller、@Repostory和@Service注解的注入Bean以及支持在指定报(及其所有子包)下使用@Autowired、@Inject和@Resource注解的bean。在context:component-scan标记中,可使用逗号、分号或空格作为分隔符来定义多个包。该标记支持组件扫描的包含和排除,从而实现更细粒度的控制。