首页 > 其他分享 >springbootMVC02(Bean加载控制)

springbootMVC02(Bean加载控制)

时间:2022-12-03 11:56:40浏览次数:39  
标签:return spring Bean new springbootMVC02 class 加载

大纲:本节的问题就是解决"spring和spring MVC要加载对应的Bean,要怎么操作"

一、思考和处理思路

二、对上面图片的总结:

三、对解决方法的"代码块"

3.1 在config包下建"springConfig"用来接收spring的Bean和建"springMvcConfig"用来接收springMvc的Bean

springMvcConfig代码块
//@Configuration 不能有这个,不然被Spring过滤掉的bean又回来了

//@ComponentScan("com.itheima.springbootmvc.controller"),写的是:你需要Bean/实体化的controller包的路径
@ComponentScan("com.itheima.springbootmvc.controller")
public class SpringMvcConfig {
}
springConfig代码块
@Configuration
//目的:spring要扫描除了controller的其他配置文件,因为controller是加载SpringMVC配置的,不是spring加载的

//方法一:指定"service"、"dao"包进行扫描
//@ComponentScan({"com.itheima.dao","com.itheima.service"})

//方法二、排除法
@ComponentScan(value = "com.itheima",
        excludeFilters = @ComponentScan.Filter(
                type = FilterType.ANNOTATION, //根据注解排除
                classes = Controller.class  //只要有@Controller这个注解,就排除
        )

)
public class SpringConfig {
}

四、对ServletContainersInitConfig进行代码块简化

ServletContainersInitConfig代码块
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

/*
这个"AbstractDispatcherServletInitializer'的底层
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    //加载springmvc配置类
    protected WebApplicationContext createServletApplicationContext() {
        //初始化WebApplicationContext对象
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //加载指定配置类:自己写的"接收Bean"的Config
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    //设置由springmvc控制器处理的请求映射路径
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //加载spring配置类
    protected WebApplicationContext createRootApplicationContext() {
        //初始化WebApplicationContext对象
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //加载指定配置类:自己写的"接收Bean"的Config
        ctx.register(SpringConfig.class);
        return ctx;
    }
 */

标签:return,spring,Bean,new,springbootMVC02,class,加载
From: https://www.cnblogs.com/chen-zhou1027/p/16947263.html

相关文章