“SpringBoot:进阶使用”的版本间差异

来自Wikioe
跳到导航 跳到搜索
(建立内容为“category:SpringBoot”的新页面)
 
无编辑摘要
 
第1行: 第1行:
[[category:SpringBoot]]
[[category:SpringBoot]]
== SpringBoot的web开发 ==
Web开发的自动配置类:“org.springframework.boot.autoconfigure.web”包中:“'''WebMvcAutoConfiguration.class'''”类;(SpringMVC的自动配置)
:[[File:spring-boot:springMVC自动配置.jpg|300px]]
=== 自动配置:ViewResolver ===
“WebMvcAutoConfiguration.class”中:(一般不需要自行配置)
<syntaxhighlight lang="java">
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
  ...
  @Configuration
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {
     ...
      private final WebMvcProperties mvcProperties;
      ...
@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix(this.mvcProperties.getView().getPrefix());
resolver.setSuffix(this.mvcProperties.getView().getSuffix());
return resolver;
}
@Bean
@ConditionalOnBean(View.class)
@ConditionalOnMissingBean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver;
}
     ...
  }
  ...
}
</syntaxhighlight>
“WebMvcProperties”(“org.springframework.boot.autoconfigure.web”包中):
<syntaxhighlight lang="java">
@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
  ...
  public static class View {
/**
* Spring MVC view prefix.
*/
private String prefix;
/**
* Spring MVC view suffix.
*/
private String suffix; 
      ...
  }
}
</syntaxhighlight>
=== 自动配置:静态资源位置 ===
全局变量中配置springMVC解析规则:
<syntaxhighlight lang="properties">
server.port=8088
server.servlet-path=/
...
</syntaxhighlight>
# “/”:Spring Boot的默认静态资源的路径为:“'''spring.resources.static-locations'''=classpath:/resources/”;
#* 可以指定为“classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/”等;
#: [[File:SpringBoot:静态文件位置配置.png|600px]]
# “*.xxx”:(或,不指定静态文件路径时)将静态资源放置到“webapp”下的“static”目录中即可通过地址访问;
#: [[File:SpringBoot默认静态文件位置.png|200px]]
=== 自定义消息转化器 ===
自定义消息转化器:只需要在“@Configuration”注解的类中,添加“@bean”注解的消息转化器方法,就会被Spring Boot自动加入到容器中:
<syntaxhighlight lang="java">
@Controller
@SpringBootApplication(exclude = { RedisAutoConfiguration.class })
@Configuration
public class HelloApplication {
  ...
  @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("ISO-8859-1"));
        return converter;
    }
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }
}
</syntaxhighlight>
系统中已有默认配置:(一般不需自行定义)
* “org.springframework.boot.autoconfigure.web”包中“HttpMessageConvertersAutoConfiguration.class”类;
<syntaxhighlight lang="java">
@Configuration
@ConditionalOnClass(HttpMessageConverter.class)
@AutoConfigureAfter({ GsonAutoConfiguration.class, JacksonAutoConfiguration.class })
@Import({ JacksonHttpMessageConvertersConfiguration.class, GsonHttpMessageConvertersConfiguration.class })
public class HttpMessageConvertersAutoConfiguration {
  ...
  @Configuration
@ConditionalOnClass(StringHttpMessageConverter.class)
@EnableConfigurationProperties(HttpEncodingProperties.class)
protected static class StringHttpMessageConverterConfiguration {
     
private final HttpEncodingProperties encodingProperties;
protected StringHttpMessageConverterConfiguration(
HttpEncodingProperties encodingProperties) {
this.encodingProperties = encodingProperties;
}
@Bean
@ConditionalOnMissingBean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
this.encodingProperties.getCharset());
converter.setWriteAcceptCharset(false);
return converter;
}
}
}
</syntaxhighlight>
=== 重写SpringMVC的配置 ===
有些时候需要自已配置SpringMVC而不是采用默认;<br/>
比如说增加一个拦截器,这个时候就得通过继承“WebMvcConfigurerAdapter.class”(“org.springframework.web.servlet.config.annotation”包)然后重写父类中的方法进行扩展:
<syntaxhighlight lang="java">
import ...
@Configuration
public class MySrpingMVCConfig extends WebMvcConfigurerAdapter{
    // 自定义拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("自定义拦截器............");
                return true;
            }
           
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                    ModelAndView modelAndView) throws Exception {
            }
           
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                    Exception ex) throws Exception {
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
    // 自定义消息转化器的第二种方法
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(converter);
    }
}
</syntaxhighlight>
== 整合 ==
== 整合Mybatis ==
== 整合Mybatis ==
== 整合Mybatis ==
== 整合Mybatis ==
== 整合Mybatis ==

2020年11月4日 (三) 04:41的最新版本


SpringBoot的web开发

Web开发的自动配置类:“org.springframework.boot.autoconfigure.web”包中:“WebMvcAutoConfiguration.class”类;(SpringMVC的自动配置)

Spring-boot:springMVC自动配置.jpg

自动配置:ViewResolver

“WebMvcAutoConfiguration.class”中:(一般不需要自行配置)

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
   ...
   @Configuration
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
	public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {
      ...
      private final WebMvcProperties mvcProperties;
      ...
		@Bean
		@ConditionalOnMissingBean
		public InternalResourceViewResolver defaultViewResolver() {
			InternalResourceViewResolver resolver = new InternalResourceViewResolver();
			resolver.setPrefix(this.mvcProperties.getView().getPrefix());
			resolver.setSuffix(this.mvcProperties.getView().getSuffix());
			return resolver;
		}

		@Bean
		@ConditionalOnBean(View.class)
		@ConditionalOnMissingBean
		public BeanNameViewResolver beanNameViewResolver() {
			BeanNameViewResolver resolver = new BeanNameViewResolver();
			resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
			return resolver;
		}
      ...
   }
   ...
}

“WebMvcProperties”(“org.springframework.boot.autoconfigure.web”包中):

@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
   ...
   public static class View {

		/**
		 * Spring MVC view prefix.
		 */
		private String prefix;

		/**
		 * Spring MVC view suffix.
		 */
		private String suffix;  
      ...
   }
}

自动配置:静态资源位置

全局变量中配置springMVC解析规则:

server.port=8088
server.servlet-path=/
...
  1. “/”:Spring Boot的默认静态资源的路径为:“spring.resources.static-locations=classpath:/resources/”;
    • 可以指定为“classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/”等;
    SpringBoot:静态文件位置配置.png
  2. “*.xxx”:(或,不指定静态文件路径时)将静态资源放置到“webapp”下的“static”目录中即可通过地址访问;
    SpringBoot默认静态文件位置.png

自定义消息转化器

自定义消息转化器:只需要在“@Configuration”注解的类中,添加“@bean”注解的消息转化器方法,就会被Spring Boot自动加入到容器中:

@Controller
@SpringBootApplication(exclude = { RedisAutoConfiguration.class })
@Configuration
public class HelloApplication {
   ...
   @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("ISO-8859-1"));
        return converter;
    }

    public static void main(String[] args) {
         SpringApplication.run(HelloApplication.class, args);
    }
}

系统中已有默认配置:(一般不需自行定义)

  • “org.springframework.boot.autoconfigure.web”包中“HttpMessageConvertersAutoConfiguration.class”类;
@Configuration
@ConditionalOnClass(HttpMessageConverter.class)
@AutoConfigureAfter({ GsonAutoConfiguration.class, JacksonAutoConfiguration.class })
@Import({ JacksonHttpMessageConvertersConfiguration.class, GsonHttpMessageConvertersConfiguration.class })
public class HttpMessageConvertersAutoConfiguration {
   ...
   @Configuration
	@ConditionalOnClass(StringHttpMessageConverter.class)
	@EnableConfigurationProperties(HttpEncodingProperties.class)
	protected static class StringHttpMessageConverterConfiguration {
      
		private final HttpEncodingProperties encodingProperties;

		protected StringHttpMessageConverterConfiguration(
				HttpEncodingProperties encodingProperties) {
			this.encodingProperties = encodingProperties;
		}

		@Bean
		@ConditionalOnMissingBean
		public StringHttpMessageConverter stringHttpMessageConverter() {
			StringHttpMessageConverter converter = new StringHttpMessageConverter(
					this.encodingProperties.getCharset());
			converter.setWriteAcceptCharset(false);
			return converter;
		}
	}
}

重写SpringMVC的配置

有些时候需要自已配置SpringMVC而不是采用默认;

比如说增加一个拦截器,这个时候就得通过继承“WebMvcConfigurerAdapter.class”(“org.springframework.web.servlet.config.annotation”包)然后重写父类中的方法进行扩展:

import ...

@Configuration
public class MySrpingMVCConfig extends WebMvcConfigurerAdapter{

    // 自定义拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("自定义拦截器............");
                return true;
            }
            
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                    ModelAndView modelAndView) throws Exception {
            }
            
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                    Exception ex) throws Exception {
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }

    // 自定义消息转化器的第二种方法
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(converter);
    }
}

整合

整合Mybatis

整合Mybatis

整合Mybatis

整合Mybatis

整合Mybatis