• 控制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. }

  • 相关阅读:
    JVM常见面试题
    C# 第五章『面向对象』◆第10节:委托
    【数据结构】哈希应用——位图、布隆过滤器
    稻草熊娱乐股价再创新低:年内累计跌幅达80%,赵丽颖曾是其股东
    「Qt中文教程指南」如何创建基于Qt Widget的应用程序(一)
    golang map 初始化 和 使用
    netcat 命令介绍及使用示例
    【方案】基于5G智慧工业园区解决方案(PPT原件)
    Stable Diffusion 本地部署教程
    300元左右的耳机哪个性价比最好、好用的开放式耳机推荐
  • 原文地址:https://blog.csdn.net/cvpatient/article/details/126015802