当前位置:网站首页>控制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[]{"/"};
}
}
边栏推荐
- 信息学奥赛一本通T1447:靶形数独
- word之图表目录中点号位置提升3磅
- 数据库表结构文档 生成工具screw的使用
- 最新版图书馆招聘考试常考试题重点事业单位
- Postman will return to the interface to generate a json file to the local
- 多线程可见
- empty() received an invalid combination of arguments - got (tuple, dtype=NoneType, device=NoneType),
- PMP每日一练 | 考试不迷路-8.2(包含敏捷+多选)
- DAC、ADC、FFT使用总结
- MySQL - 触发器
猜你喜欢
随机推荐
计算机网络常见面试题总结
华为设备配置BFD状态与接口状态联动
数据仓库指标体系实践
Shell脚本之一键安装mysql
6.nodejs--promise、async-await
【第1天】SQL快速入门-基础查询(SQL 小虚竹)
调用feign报错openfeign/feign-core/10.4.0/feign-core-10.4.0.jar
Data warehouse buried point system and attribution practice
海思项目总结
mysql慢查询优化
idea远程debug
ORB-SLAM2提取特征点
关于NOI 2022的报到通知
924. 尽量减少恶意软件的传播 前缀和
9月考,如何选择靠谱正规的培训机构?
【Shell】3万字图文讲解带你快速掌握shell脚本编程
Embedding two implementations of the torch code
[机缘参悟-59]:《素书》-6-安于礼仪[安礼章第六]
Cesium loads offline maps and offline terrain
贷中存量客户的价值挖掘与分类实现,试试这一重要的场景模型









