当前位置:网站首页>控制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[]{"/"};
}
}
边栏推荐
猜你喜欢
jvm 面试题
Getting Started with Chrome Plugin Development
RHCSA第四天
现货黄金分析的主要流派
torch.nn.modules.activation.ReLU is not a Module subclass
华为设备配置BFD状态与接口状态联动
El - tree set using setCheckedNodessetCheckedKeys default check nodes, and a new check through setChecked specified node
Cesium loads offline maps and offline terrain
【playwright】pytest-playwright增加代理服务选项
spark中的cache和checkpoint
随机推荐
薛定谔的对象属性判断
被数据分析重塑的5个行业
spark中Repartition 和 Coalesce 区别
mongodb的shell脚本
用代码构建UI界面
Flutter | 判断 Text 组件是否显示完
【着色器实现Glow可控局部发光效果_Shader效果第十三篇】
Oracle Rac 集群文件目录迁移
LiveData 记录下 +
最新版图书馆招聘考试常考试题重点事业单位
解读 refresh 十二步骤
PHP 获取服务器信息
帆软11版本参数联动为null查询全部
MySQL必知必会
一文搞懂什么是@Component和@Bean注解以及如何使用
我国有关信息方面的法律法规
C语言实现通讯录功能(400行代码实现)
【图像边缘检测】基于matlab灰度图像的积累加权边缘检测【含Matlab源码 2010期】
【OpenCV】 - 显示图像API之imshow()对不同位深度(数据类型)的图像的处理方法
(十五)51单片机——呼吸灯与直流电机调速(PWM)