1. 程式人生 > 遊戲 >《樂高星戰:天行者傳奇》可操作角色超過300名

《樂高星戰:天行者傳奇》可操作角色超過300名

技術標籤:springbootspring boot

總結

springboot如何開啟自動配置

1、main方法所在類的@SpringBootApplication註解

@SpringBootApplication       <-----------------註解
public class SpringbootQuickApplication {
    public static void main(String[] args)
{ SpringApplication.run(SpringbootQuickApplication.class,args); } }

2、點進去註解類上有一個@EnableAutoConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration	 <--------------註解 
@ComponentScan(
    excludeFilters =
{@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} )

3、點進註解類上有一個註解

			@Import{AutoConfigurationImportSelector.class}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
    Class<?>[] exclude() default {};
    String[] excludeName() default {};
}

在AutoConfigurationImportSelector類中會執行getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes)方法裡面有一行:
List configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
這裡就會掃描具有MEAT-INF/spring.factories檔案的jar包,得到所有的配置類:

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
 AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames
    	(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
       return configurations;
}

4、找到spring.factories檔案的內容看下

在這裡插入圖片描述

4.1、spring.factories自動注入的內容


# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\

4.2、解釋幾個註解

@SpringBootApplication:啟動stringboot環境 
@ComponentScan:配置包掃描
@ImportResource:引入自定義配置檔案

springboot如何處理異常的

1 、自定義錯誤頁面

 如 果 我 們 需 要 將 所 有 的 異 常 同 一 跳 轉 到 自 定 義 的 錯 誤 頁 面 
  需 要 再src/main/resources/templates 目錄下建立 error.html 頁面。注意:名稱必須叫 error
<!DOCTYPE html>
<html>
  <head>
   <meta charset="UTF-8">
   <title>錯誤提示頁面</title>
  </head>
  <body>
   錯了 我不giao了
   <span th:text="${exception}"></span>
  </body>
</html>

2、@ExceptionHandle 註解處理異常

上一種方法不管發生什麼異常,都只能跳轉到一個頁面,顆粒度太大而這一種方式可以實現對不同的異常做不同的處理

@Controller
public class DemoController {
	@RequestMapping("/show")
	public String showInfo(){
			String str = null;
			str.length();
		return "index";
	}
	@RequestMapping("/show2")
	public String showInfo2(){
			int a = 10/0;
		return "index";
	}
// 算數錯誤	
@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView arithmeticExceptionHandler(Exception e){
	ModelAndView mv = new ModelAndView();
		mv.addObject("error", e.toString());
		mv.setViewName("error1");
	return mv;
	}

//空指標異常
@ExceptionHandler(value={java.lang.NullPointerException.class})
public ModelAndView nullPointerExceptionHandler(Exception e){
	ModelAndView mv = new ModelAndView();
		mv.addObject("error", e.toString());
		mv.setViewName("error2");
	return mv;
	}

頁面1

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>錯誤提示頁面-ArithmeticException</title>
 </head>
 <body>
  出錯了,請與管理員聯絡。。。
  <span th:text="${error}"></span>
 </body>
</html>

頁面2

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>錯誤提示頁面-NullPointerException</title>
 </head>
 <body>
  <span th:text="${error}"></span>
 </body>
</html>

3、@[email protected] 註解處理異常

上一種方式必須要在每一個Controler裡面重複寫異常處理程式碼,程式碼複用性太差,這一種方法可以實現異常的全域性處理。需要建立一個能夠處理異常的全域性異常類。在該類上需要新增@ControllerAdvice 註解

@ControllerAdvice
public class GlobalException {

	//java.lang.ArithmeticException
	@ExceptionHandler(value={java.lang.ArithmeticException.class})
	public ModelAndView arithmeticExceptionHandler(Exception e){
			ModelAndView mv = new ModelAndView();
				mv.addObject("error", e.toString());
				mv.setViewName("error1");
			return mv;
		}
		
	//java.lang.NullPointerException
	ExceptionHandler(value={java.lang.NullPointerException.class})
	public ModelAndView nullPointerExceptionHandler(Exception e){
			ModelAndView mv = new ModelAndView();
				mv.addObject("error", e.toString());
				mv.setViewName("error2");
			return mv;
		}
	}
}	

4、配置 SimpleMappingExceptionResolver 處理異常

//通過 SimpleMappingExceptionResolver 做全域性異常處理
@Configuration
public class GlobalException {


//該方法必須要有返回值。返回值型別必須是:SimpleMappingExceptionResolver
@Bean
public SimpleMappingExceptionResolver
	getSimpleMappingExceptionResolver(){
			SimpleMappingExceptionResolver resolver = new
			SimpleMappingExceptionResolver();
		Properties mappings = new Properties();
		/**
		* 引數一:異常的型別,注意必須是異常型別的全名
		* 引數二:檢視名稱
		*/
		mappings.put("java.lang.ArithmeticException", "error1");
		mappings.put("java.lang.NullPointerException","error2");
		//設定異常與檢視對映資訊的
		resolver.setExceptionMappings(mappings);
		return resolver;
	}
}

5、自定義 HandlerExceptionResolver 類處理異常

/**
* 通過實現 HandlerExceptionResolver 介面做全域性異常處理
*/
@Configuration
public class GlobalException implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler,Exception ex) {
		ModelAndView mv = new ModelAndView();
		//判斷不同異常型別,做不同檢視跳轉
		if(ex instanceof ArithmeticException){
			mv.setViewName("error1");
		}
		if(ex instanceof NullPointerException){
			mv.setViewName("error2");
		}
		mv.addObject("error", ex.toString());
		return mv;
	}
}

在springboot中,如何使用攔截器?

1、實現攔截器

public class InterceptorDemo extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, 			Object o) throws Exception {
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        System.out.println("前置攔截器1 preHandle: 請求的uri為:"+requestURL.toString());
        return true;
    }
     @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object 		o, ModelAndView modelAndView) throws Exception {
        System.out.println("攔截器1 postHandle: ");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, 		Object o, Exception e) throws Exception {
        System.out.println("攔截器1 afterCompletion: ");
    }
}

2、註冊攔截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
	
    //註冊自定義攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InterceptorDemo2()).addPathPatterns("/**");
        registry.addInterceptor(new InterceptorDemo()).addPathPatterns("/**");
    }
 }

在springboot中,如何擴充套件springmvc的功能

@Configuration  		<-----註解 
public class WebMVCConfig implements WebMvcConfigurer {   <----實現WebMvcConfigurer

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/index").setViewName("index");
        //定義跳轉到主頁面的檢視
        registry.addViewController("/dashboard.html").setViewName("dashboard");
    }

    
}