1. Controller加载控制
因为功能不同,要避免Spring错误的加载到SpringMVC的bean
1.1 Controller加载控制与业务bean加载控制
SpringMVC相关bean(表现层bean)
Spring控制的bean
- 业务bean(Service)
- 功能bean(DataSource等)
SpringMVC相关bean加载控制
- SpringMVC加载的bean对应的包均在com.zhang.controller包内
Spring相关bean加载控制
- 方式一:Spring加载的bean设定扫描范围为com.zhang,排除掉controller包内的bean
- 方式二:Spring加载的bean设定扫描范围为精准范围,例如service包、dao包等
- 方式三:不区分Spring与SpringMVC的环境,加载到同一个环境中
1.2 加载Spring控制的bean的时候排除掉SpringMVC控制的bean(方式一)
名称:@ComponentScan
类型:类注解
范例
package com.zhang.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@Configuration
@ComponentScan(value = "com.zhang", excludeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
))
public class SpringConfig {
}
属性
- excludeFilters:排除扫描路径中加载的bean,需要指定类别(type)与具体项(classes)
- includeFilters:加载指定的bean,需要指定类别(type)与具体项(classes)
1.3 验证是否排除成功
创建spring容器加载spring配置文件,然后根据类型获取表现层的bean,如果不能获取则证明加载Spring控制的bean的时候成功排除掉SpringMVC控制的bean;这里值得一提的是,需要把SpringMVCConfig配置类上的@Configuration注释掉;
package com.zhang;
import com.zhang.config.SpringConfig;
import com.zhang.controller.UserController;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserController userController = context.getBean(UserController.class);
System.out.println(userController);
}
}
1.4 运行结果
证明加载Spring控制的bean的时候成功排除掉SpringMVC控制的bean
2. Bean的加载格式
extends AbstractDispatcherServletInitializer
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringConfig.class);
return ctx;
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
简化格式
extends AbstractAnnotationConfigDispatcherServletInitializer
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class}
};
protected String[] getServletMappings() {
return new String[]{"/"};
}
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
}
到此这篇关于Spring bean加载控制实现方法的文章就介绍到这了,更多相关Spring bean加载控制内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!