前言
前面的章节我们讲解了Spring应用上下文的两种配置方式,分别是xml文件配置,混合配置。有些时候,我们不得不使用混合配置,因为仅仅使用java编程配置,无法达到我们的期望,这些场景我们在后续的章节会详细讲解。前面章节所讲解的混合配置不是必须的,它完全可以修改为纯java编程配置。之所以使用混合配置,仅仅是处于演示的目的。
根应用上下文配置
package com.gxz.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
@Configuration
@ComponentScan(
basePackages = "com.gxz",
useDefaultFilters = false,
includeFilters = @ComponentScan.Filter(Service.class)
)
public class RootContextConfig
{
}
Java编程方式配置应用上下文,首先,Java配置类标上注解@Configuration,表示这是一个Java配置类,用于配置Spring应用上下文。必须要提醒的是,注解@Configuration是@Component的具体注解。也就是说,凡是标注了@Configuration的实现类,会被Spring认为是一个配置bean,在Web容器启动的时候,Spring会自动进行实例化会注入依赖。所以,我们不能手工配置让Spring的组件再次扫描到它,并对其进行实例化。因为,这样会造成重复实例化。在根应用上下文和DispatcherServlet应用上下文的配置中,组件扫描分别被配置为仅仅扫描Service
bean和Controller bean,这样一来,虽然Configuration bean所在的包是com.gxz.config,是com.gxz的子包,但是因为包含过滤器的存在,使之不被扫描器扫描到。本章节中,根应用上下文和DispatcherServlet应用上下文的配置内容和前面的章节保持一致,只不过形式不一样罢了。
以下xml文件配置和java编程配置效果是一样的。
<context:annotation-config />
<context:component-scan base-package="com.gxz" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
@ComponentScan(
basePackages = "com.gxz",
useDefaultFilters = false,
includeFilters = @ComponentScan.Filter(Service.class)
)
我们注意到,xml文件配置中,有这样的配置<context:annotation-config /> ,但到了java编程配置,却没有对应的配置。此处,java编程配置不需要显式有此项配置。
DispatcherServlet应用上下文的配置
package com.gxz.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan(
basePackages = "com.gxz",
useDefaultFilters = false,
includeFilters = @ComponentScan.Filter(Controller.class)
)
public class DispatcherServletContextConfig
{
}
以下xml文件配置和java编程配置效果是一样的。
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.gxz" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
@EnableWebMvc
@ComponentScan(
basePackages = "com.gxz",
useDefaultFilters = false,
includeFilters = @ComponentScan.Filter(Controller.class)
)