当前位置:网站首页>控制bean的加载
控制bean的加载
2022-08-03 06:34:00 【bobo洁厕灵】
在配置类(*config)中,需要加载资源(component-sacn)

controller、service和dao这些类都需要被容器管理成bean对象,SpringMVC或者Spring加载这些bean可以控制加载要求
让实现类bean对应的功能能够被需要这个功能的框架来加载这个实现类bean
SpringMVC加载其相关bean(表现层bean),也就是controller包下的类
Spring控制的bean
业务bean(Service)
功能bean(DataSource,SqlSessionFactoryBean,MapperScannerConfigurer等)
如何让Spring,SpringMVC加载各自的内容?
在SpringMVC的配置类SpringMvcConfig中使用注解@ComponentScan,只需要将其扫描范围设 置到controller即可,如
@Configuration
@ComponentScan("com.itheima.controller")
public class SpringMvcConfig {
在Spring的配置类SpringConfig中使用以下方式,避开controller
@Configuration
@ComponentScan({"com.itheima.service","comitheima.dao"})
public class SpringConfig {
}也可以通过以下方式避开controller
@Configuration
@ComponentScan(value="com.itheima",
[email protected](
type = FilterType.ANNOTATION,
classes = Controller.class
)
)
public class SpringConfig {
}
注意,SpringMVC的配置类如果在Spring配置类的扫描范围之下,情况发生变化,因为你在Spring的配置类中设置避开扫描controller,但是扫描到了SpringMVC的配置类,这个配置类中可以扫描到controller。
解决办法是将SpringMVC的配置类移出Spring的扫描范围
获取AnnotationConfigWebApplicationContext对象的简单方法
public class ServletContainersInitConfig extends
AbstractDispatcherServletInitializer {
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new
AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
优化写法:
将AbstractDispatcherServletInitializer更换为AbstractAnnotationConfigDispatcherServletInitializer ,再实现接口的三个方法,登记注册类,以下三个方法中的写法更为方便,不需手动的register配置类
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[]{"/"};
}
}
边栏推荐
猜你喜欢
随机推荐
一篇文章教你写扫雷(c语言基础版)
(十五)51单片机——呼吸灯与直流电机调速(PWM)
模型训练前后显卡占用对比、多卡训练GPU占用分析【一文读懂】
924. 尽量减少恶意软件的传播 前缀和
解决登录vCenter提示“当前网站安全证书不受信任“
MySQL日期和时间戳的转换
华为设备配置BFD状态与接口状态联动
excel高级绘图技巧100讲(二十一)- Excel层叠柱形图
标准输入流
被数据分析重塑的5个行业
死锁的成因和对应的解决方案
Week5
数据库表结构文档 生成工具screw的使用
pgaudit 的安装使用《postgresql》
jvm 面试题
链表之打基础--基本操作(必会)
information_schema
信息学奥赛一本通T1448:深搜的剪枝技巧 电路维修
Cesium loads offline maps and offline terrain
static数据成员









