• 控制bean的加载


    在配置类(*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即可,如

    1. @Configuration
    2. @ComponentScan("com.itheima.controller")
    3. public class SpringMvcConfig {

    在Spring的配置类SpringConfig中使用以下方式,避开controller

    1. @Configuration
    2. @ComponentScan({"com.itheima.service","comitheima.dao"})
    3. public class SpringConfig {
    4. }

    也可以通过以下方式避开controller

    1. @Configuration
    2. @ComponentScan(value="com.itheima",
    3. excludeFilters=@ComponentScan.Filter(
    4. type = FilterType.ANNOTATION,
    5. classes = Controller.class
    6. )
    7. )
    8. public class SpringConfig {
    9. }

    注意,SpringMVC的配置类如果在Spring配置类的扫描范围之下,情况发生变化,因为你在Spring的配置类中设置避开扫描controller,但是扫描到了SpringMVC的配置类,这个配置类中可以扫描到controller。

    解决办法是将SpringMVC的配置类移出Spring的扫描范围

    获取AnnotationConfigWebApplicationContext对象的简单方法

    1. public class ServletContainersInitConfig extends
    2. AbstractDispatcherServletInitializer {
    3. protected WebApplicationContext createServletApplicationContext() {
    4. AnnotationConfigWebApplicationContext ctx = new
    5. AnnotationConfigWebApplicationContext();
    6. ctx.register(SpringMvcConfig.class);
    7. return ctx;
    8. }
    9. protected String[] getServletMappings() {
    10. return new String[]{"/"};
    11. }

    优化写法:

    将AbstractDispatcherServletInitializer更换为AbstractAnnotationConfigDispatcherServletInitializer   ,再实现接口的三个方法,登记注册类,以下三个方法中的写法更为方便,不需手动的register配置类

    1. public class ServletContainersInitConfig extends
    2. AbstractAnnotationConfigDispatcherServletInitializer {
    3. protected Class[] getRootConfigClasses() {
    4. return new Class[]{SpringConfig.class};
    5. }
    6. protected Class[] getServletConfigClasses() {
    7. return new Class[]{SpringMvcConfig.class};
    8. }
    9. protected String[] getServletMappings() {
    10. return new String[]{"/"};
    11. }
    12. }

  • 相关阅读:
    基于springboot实现在线小说阅读平台系统【项目源码】计算机毕业设计
    《算法系列》之 数组
    自动化测试框架 —— pytest框架入门篇
    SQL 常见函数整理 _ Stuff() 替换字符串中的一部分字符
    springcloud 知识总结
    Python操作lxml库(基础篇)
    9月【笔耕不辍】勋章活动获奖名单公布
    值得注意的: c++动态库、静态库、弱符号__attribute__((weak))以及extern之间的关系
    C++中vector用法总结
    大语言模型(一)OLMo
  • 原文地址:https://blog.csdn.net/cvpatient/article/details/126015802