springMVC全注解开发

消除springmvc.xml

创建配置类

@Configuration
@ComponentScan({"com.java.service", "com.java.web.controller"})
@EnableWebMvc//<mvc:annotation-driven/> <mvc:default-servlet-handler/>
public class MyConfigClass {
    /**
     * 文件上传解析器 id固定为multipartResolver
     * <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
     *
     * @return
     */
    @Bean("multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("UTF-8");
        commonsMultipartResolver.setMaxUploadSize(102400);
        return commonsMultipartResolver;
    }
}

定义一个类继承AnnotationConfigWebApplicationContext,在自定义类的构造里注册核心配置类:

public class MyAnnotationApplicationContext extends AnnotationConfigWebApplicationContext {
    public MyAnnotationApplicationContext() {
        //注册配置类
        super.register(MyConfigClass.class);
    }
}

在web.xml配置前端处理器的位置初始化配置类:

<init-param>
    <!--加载配置类-->
    <param-name>contextClass</param-name>
    <param-value>com.java.config.MyAnnotationApplicationContext</param-value>
</init-param>

消除web.xml

创建自定义类继承抽象类AbstractAnnotationConfigDispatcherServletInitializer,并且实现里面的抽象方法:

public class MyAbstractAnnotationConfigDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    //加载spring的配置类
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{MySpringConfigClass.class};
    }

    @Override
    //加载springmvc配置类
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{MySpringMvcConfigClass.class};
    }

    @Override
    //加载前端处理器的映射路径
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

删除web.xml,发现运行正常,消除成功!

posted @ 2023-03-02 20:48  Liku007  阅读(55)  评论(0编辑  收藏  举报