20200209——springboot mvc配置原理

Configuration

从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

正常来说,以前我们进行Springmvc配置的时候是,

  @Test
    public void  run1(){
        //加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //获取对象
        AccountService accountService = (AccountService) applicationContext.getBean("accountService");
        //调用方法
        accountService.findAll();
    }

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)

package com.dxz.demo.configuration;

import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {
    public TestConfiguration() {
        System.out.println("TestConfiguration容器启动初始化。。。");
    }
}

两个代码是等价的

package com.dxz.demo.configuration;

import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {
    public TestConfiguration() {
        System.out.println("TestConfiguration容器启动初始化。。。");
    }
}

如果你想diy一些定制化的功能或者只需要写这个组件,然后将它交给springboot

springboot会帮助我们自动装配

springboot的视图解析器

package com.mmz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

/**
 * @Classname MyMvcConfig
 * @Description 全面接管/扩展Springmvc
 * @Date 2020/2/9 18:12
 * @Created by mmz
 */

@Configuration
public class MyMvcConfig  implements WebMvcConfigurer {

    @Bean
    public ViewResolver myMyViewResolver(){
        return new MyViewResolver();
    }

    //自定义了一个视图解析器
    public static class MyViewResolver implements ViewResolver{
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }

}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了735 篇原创文章 · 获赞 42 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_36344771/article/details/104238671