Controller加载控制与业务bean加载控制
因为功能不同,如何避免Spring错误的加载到SpringMVC的bean?
在加载Spring控制的bean的时候排除掉SpringMVC控制的bean
1. 方法一
//设置spring配置类加载bean时的过滤规则,当前要求排除掉表现层对应的bean
//excludeFilters属性:设置扫描加载bean时,排除的过滤规则
//type属性:设置排除规则,当前使用按照bean定义时的注解类型进行排除
//classes属性:设置排除的具体注解类,当前设置排除@Controller定义的bean
@ComponentScan(value="com.itheima",
excludeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
)
)
2. 方法二
在SpringConfig下的扫描目录中设置精准范围
@ComponentScan({"com.itheima.service","com.itheima.dao"})
最后,Tomcat启动时,需要加载Spring和SpringMVC的配置,所以需要进行配置,让Tomcat启动时加载Spring和SpringMVC配置,分别加载两个容器
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[]{"/"};
}
}
可以做出相应的简化
让ServletContainersInitConfig
继承AbstractAnnotationConfigDispatcherServletInitializer
,实现对应的抽象方法
//web配置类简化开发,仅设置配置类类名即可
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//设置拦截路径
protected String[] getServletMappings() {
return new String[]{"/"};
}
}