当前位置:网站首页>控制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[]{"/"};
}
}
边栏推荐
猜你喜欢
随机推荐
ISIJ 2022收官,中国初中生再展风采
第五章:指令集
ORB-SLAM2提取特征点
qt学习之旅--MinGW32编译opencv3.0.0
从学生到职场的转变
线程基础(二)
2022年 SQL 优化大全总结详解
信息学奥赛一本通T1452:Keyboarding
2022用户画像构建
postman将接口返回结果生成json文件到本地
华为设备配置BFD与接口联动(触发与BFD联动的接口物理状态变为Down)
Postman will return to the interface to generate a json file to the local
postman将接口返回结果生成csv文件到本地
spark中的bykey
excel高级绘图技巧100讲(二十一)- Excel层叠柱形图
C语言版本和GCC版本
DIFM network, rounding and repetition
【第1天】SQL快速入门-基础查询(SQL 小虚竹)
【图像去雾】基于matlab暗通道和非均值滤波图像去雾【含Matlab源码 2011期】
分布式数据库数据一致性的原理、与技术实现方案









