Controller加载控制与业务bean加载控制

Controller加载控制与业务bean加载控制

  • SpringMVC相关bean(表现层bean)

  • Spring控制的bean

    1. 业务bean(Service)

    2. 功能bean(DataSource等)

  • SpringMVC相关bean加载控制

    1. SpringMVC加载的bean对应的包均在com.itheima.controller包内

  • Spring相关bean加载控制

    1. 方式一:Spring加载的bean设定扫描范围为com.itheima,排除掉controller包内的bean

    2. 方式二:Spring加载的bean设定扫描范围为精准范围,例如service包、dao包等

    3. 方式三:不区分Spring与SpringMVC的环境,加载到同一个环境中

方式一代码实现

  • 名称:@ComponentScan

  • 类型:类注解

  • 范例

    @Configuration
    @ComponentScan(value = "com.itheima",
                   excludeFilters = @ComponentScan.Filter(
                       type = FilterType.ANNOTATION,
                       classes = Controller.class   //Controller ---> import org.springframework.stereotype.Controller;
                   )
                  )
    public class SpringConfig {
    }
  • 属性

    1. excludeFilters:排除扫描路径中加载的bean,需要指定类别(type)与具体项(classes)

    2. includeFilters:加载指定的bean,需要指定类别(type)与具体项(classes)

Bean的加载格式

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer { 
    protected WebApplicationContext createServletApplicationContext() { 
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;  
    }   
    protected WebApplicationContext createRootApplicationContext() {  
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();      
        ctx.register(SpringConfig.class);        
        return ctx;  
    }   
    protected String[] getServletMappings() { 
        return new String[]{"/"}; 
    }
}

简化格式

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    };
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
}

 

posted @ 2022-06-30 14:01  happyZHF  阅读(165)  评论(0)    收藏  举报