SpringMVC 프로젝트를 SpringBoot로 전송하는 과정에서 다음과 같은 작업이 주로 수행되었습니다.
이 기사는 무엇을 어떻게하고 어떻게 해야하는지 소개하는 것 외에도 불필요한 말도 안되는 많은 것을 가질 것입니다. 원칙에 대한 논의의 경우 그 이유도 알아야합니다.
프로필 구성
기존의 스프링 프로젝트에서 여러 프로파일의 구성 방법은 POM.XML 파일에 여러 프로파일을 작성한 다음 프로젝트를 시작하기 전에 Maven 파일을 실행하여 선택한 프로파일 환경을 사전로드하는 것입니다. 로드 후 프로젝트를 실행할 때로드 된 환경에 따라 전역 변수에로드 할 .properties 파일을 결정합니다.
SpringBoot에서 여러 프로파일을 관리하는 것은 매우 간단합니다.
명령 줄을 사용하여 JAR 패키지를 실행할 때 프로파일을 선택할 수 있습니다.
java -jar example.jar -spring.profiles.active = test
또는 Global Configuration Application.Properties에서 구성하십시오
spring.profiles.active = application.properties에서 테스트를 추가하십시오
위의 두 가지 방법은 "테스트"프로파일을 시작할 수 있으며, 전자는 후자보다 실행이 우선 순위가 높습니다.
(그건 그렇고, SpringBoot 에서이 두 가지 방법은 기본적으로 "외부 구성"메소드를 사용하여 환경을 편집하고 교체합니다)
또한 각각의 독립적 인 프로파일은 각각의 다른 환경에 대해 "Application-XXX.Properties"형식으로 구성됩니다.
프로필이 정상적으로로드되어 있는지 테스트 해야하는 경우 해당 .properties 파일에 쓸 수 있습니다.
Server.port = 9080
이 포트가 스타트 업에서 시작되었는지 확인할 수 있습니다.
여기에서 springboot가 구성 파일을로드하는 순서를 언급 할 수 있습니다.
글로벌 변수는 속성 파일에서 읽습니다
이전 섹션에서는 다양한 환경에 대한 속성 구성을 작성했습니다. 여기서 우리는 이러한 속성이 글로벌 변수로 기록되어 있는지에 대해 쓸 것입니다. 이는 나중에 다른 장소에서 직접 통화에 편리합니다.
/*** 글로벌 변수*/public class global {public static string examppath; @Value ( "$ {example_path}") public void setexamplePath (문자열 예) {global.examplePath = examplePath; }} 이런 식으로 .properties 파일을
example_path = http : // localhost : 9090
이 속성은 글로벌 변수로 읽습니다.
데이터 소스 및 mybatis 구성
전통적인 스프링 프로젝트에서는 mybatis를 사용하여 데이터베이스에 연결하십시오.
이 모든 것은 XML 구성 파일로 구성되어 있으며 이는 매우 번거 롭습니다. SpringBoot에서는 이러한 XML 구성을 피하십시오.
Mybatis는 이제 SpringBoot를 지원했습니다. 우리는 mybatis-spring-boot-starter 종속성 만 추가하면 다음을 수행 할 것입니다.
따라서 SpringBoot의 MyBatis 구성에서는 다음을 수행해야합니다.
Application- {profile} .properties에서 데이터베이스 정보를 작성하십시오.
spring.datasource.url = jdbc : oracle : thin :@// localhost : 1234/examplespring.datasource.username = rootspring.datasource.password = 123456spring.datas ource.driver-class-name = oracle.jdbc.driver.oracledriverspring.datasource.maxactive = 10spring.datasource.maxidle = 5spring.datasource.maxwait = -1
이런 식으로, 우리는 스프링 컨텍스트에 데이터 소스 Bean을 등록합니다.
MyBatisconFig 파일을 만들고 XML을 Java로 바꾸십시오.
/*** Wutaoyu가 2017/12/7에 만들었습니다. */@configuration@enableTransactionManagement@mapperscan ( "com.example.db.dao") 공개 클래스 MyBatisconFig {@autowired private dataSource dataSource; @Bean (name = "sqlsessionFactory") public sqlsessionFactory sqlsessionFactoryBean () {sqlsessionFactoryBean sqlsession = new SqlSessionFactoryBean (); sqlsession.setdatasource (dataSource); {// XML 디렉토리 추가 resourcepatternresolver resolver = new PathMatchingResourcepatternresolver (); sqlsession.setMapperLocations (resolver.getResources ( "classPath : 매핑/*. XML"); 반환 sqlsession.getObject (); } catch (예외 e) {e.printstacktrace (); 새로운 runtimeexception (e)을 던지십시오. }} @bean public sqlsessiontemplate sqlsessiontemplate (sqlsessionFactory sqlsessionFactory) {return new sqlsessionTemplate (sqlsessionFactory); } @bean public platformtransactionManager annotationDriventRansactionManager () {return new DataSourCetransactionManager (DataSource); } @Bean (name = "examplequence") public oraclesequencemaxvalueincrementer examplequencebean () {oraclesequencemaxvalueincrementer examplesequence = new oraclesequencemaxvalueincrementer (); exampleSequence.setIncrementerName ( "example_seq"); ExampleSequence.SetDatasource (DataSource); 반환 예비 판결; }} @mapperscan 은이 패키지 아래의 맵퍼를 스캔해야합니다.
또한 Mapper.xml의 위치는 자원 폴더 아래에 매핑 폴더를 만들고 아래에 배치하는 것입니다.
여기의 기능은 XML과 유사합니다. .java 파일의 기존 XML 표현 방법을 설명하고 본질적으로 데이터 소스를 단계별로 주입하는 것입니다.
이 예제는 Oracle 데이터베이스를 사용하므로 마지막 emavequence는 시퀀스를 추가하는 방법을 설명하는 예입니다.
모든 매퍼 @mapper에 대한 인터페이스 주석
예를 들어:
@MapperPublic Interface usermapper {...} 로그 파일 구성
로그백은 속성 형태의 외부 구성을 지원하지만 비교적 상세한 구성의 경우 XML 구성을 사용해야합니다.
XML 파일이 .properties 파일에서 일부 경로를 읽으려면 자주 수정이 필요할 수있는 정적 구성이 필요합니다. logback-spring.xml에서 구성해야합니다.
<property resource = "application.properties" /> <속성 이름 = "log.root.level"value = "$ {log.root.level}" /> <속성 이름 = "log.path"value = "$ {log.path}" /> <속성 이름 = "log.modulename"value = "$ {log.module}" /> 이렇게하면 Application.Properties 파일을
log.path =/home/logs/emableg.root.level = infolog.Module = 예제
logback-spring.xml로 읽은 다음 호출하십시오.
WebConfig 구성
WebConfig의 주요 기능은 일부 기본 구성을 위해 Web.xml 및 Spring-MVC.xml을 대체하는 것입니다.
1. web.xml 정보
전통적인 스프링 프로젝트는 모두 web.xml 파일을 구성합니다. 이 파일의 기능은 다음과 같습니다. 전쟁 패키지를 Application 컨테이너 (예 : Tomcat)에 넣을 때 컨테이너는 필터 (필터), 서블릿, 오류 페이지, 환영-리스트, 리스너 (리스너), 컨텍스트-파라 (컨텍스트 매개 변수), Resource-Ref (Resource Configuration) 및 Web.xml에 따른 기타 구성을로드합니다.
ContextLoaderListener를 포함한 리스너는 컨테이너를 시작할 때 ApplicationContext의 구성 정보를 자동으로 조립하기 위해 여기에로드됩니다.
<Leater> <Leater-Class> org.springframework.web.context.contextloaderListener </Leater-Class> </largeer>
이 ApplicationContext는 Spring IOC의 핵심이며 (BeanFactory에서 상속) 모든 Singleton Bean은 현재 인스턴스화됩니다.
또한 SpringMVC의 매우 중요한 Dispatcherservlet도 여기에로드되며 Dispatcherservlet을 구성 할 XML 파일이 결정됩니다.
<Servlet> <servlet-name> springmvc </servlet-name> <servlet-class> org.spramework.web.servlet.dispatcherservlet </servlet-class> <init-param> <param-name> contextConfiglocation </param-name> <param-value> classml </param-mvc.xml <load-on-startup> 1 </load-on-startup> <!-<Async-supported> true </async-supported>-> </servlet>
2. Spring-MVC.xml에 대해
Spring-mvc.xml은 SpringMVC 구성 파일입니다. 여기서는 ViewResolver, Multipartresolver, HTTP 메시지 변환기, 사용자 정의 인터셉터 등과 같이 사용자 정의 해야하는 Bean을 구성 할 수 있습니다.
위의 모든 부분은 SpringBoot와 아무 관련이 없으며 주로 이유와 이유를 알기위한 것입니다. 관심이 없다면 무시할 수 있습니다.
SpringBoot 구성에 대해 이야기 해 봅시다. SpringBoot는 "컨벤션이 구성보다 낫다"는 말을 가지고 있으며, 이는 구체적으로 타겟팅 된 구성 (특수 구성이 필요한 경우 구성)이 아닌 합의 된 방법을 사용하는 것을 의미합니다.
스프링 부트 스타터-웹의 "상자 밖으로"의존성을 도입 한 후 스프링 부트 스타터-위스는 스프링 부트 오토 컨퍼런스가 포함되어 있습니다.
이 종속성으로 @enableautocongiguration 주석을 사용할 수 있습니다. 이 주석은 소개 된 종속성을 기반으로 필요한 스프링 구성을 추측하고 구성하는 데 도움이됩니다. 스프링 부트 스타터 -WEB가 도입 되었으므로이 주석은 웹 관련 구성을 구성합니다.
또한 @EnableAutoCongiguration 주석이 @SpringBootApplication 주석에 포함되었습니다. 따라서 시작 클래스 exampleServerApplication에서 @SpringBootApplication을 주석 만 해제하면 웹을 자동으로 구성하여 구성 할 수 있습니다.
물론, 우리는 몇 가지 특별한 구성이있을 수 있으며 현재로서는 사용자 정의 할 webConfig를 만들 수 있습니다.
/*** Wutaoyu가 2017/12/8에 만들었습니다. */ @configurationPublic Class WebConfig는 WebMvcConfigurerAdapter {@OverRide public void configureMessAgeConverters (list <httpmessageConverter <?>> converters) {converter.add (MarshallinghttpmessageConverter (MarshallinghttpmessageConverter (MarshallinghttpmessageConverter)); } public marshallinghttpmessageconverter marshallinghttpmessageconverter () {MarshallinghttpmessageConverter marshallinghttpmessageconverter = new MarshallinghttpmessageConverter (); List <MediaType> mediaTypes = new ArrayList <MediaType> (); mediaTypes.Add (mediaType.text_xml); mediaTypes.Add (mediaType.Application_xml); xstreammarshaller xstreammarshaller = new xstreammarshaller (); MarshallinghttpmessageConverter.setSupportedMediAtypes (mediaTypes); MarshallinghttpMessageConverter.setMarShaller (XStreamMarshaller); MarshallinghttpmessageConverter.setunmarshaller (xstreammarshaller); MarshallinghttpMessageConverter를 반환합니다. } // 구성 파일 업로드 @Bean (이름 = { "multipartresolver"}) public multipartresolver multipartresolver () {Commonsmultipartresolver Commonsmultipartresolver = 새로운 Commonsmultipartresolver (); Commonsmultipartresolver.setDefaultEncoding ( "UTF-8"); Commonsmultipartresolver.setmaxuploadsize (10485760000L); Commonsmultipartresolver.setmaxinmemorysize (40960); Commonsmultipartresolver를 반환합니다. } // 예외 처리 @Bean Public ExceptionHandler ExceptionResolver () {ExceptionHandler ExceptionHandler = new ExceptionHandler (); Return Exception Handler; } // interceptor @override public void addinterceptors (interceptorregistry registry) {registry.addinterceptor (new loginterceptor ()). AddPathPatterns ( "/**"); super.addinternceptors (레지스트리); }}이 샘플 파일에서 몇 가지 작업을 수행했습니다.
과도한 콩 주입을 제거하십시오
이것은 산만하지만 실제로 발생한 문제 중 하나이기도합니다.
실제로 SpringBoot Project를 실행할 때, 나는 불필요한 Bean 주입 인 전통적인 스프링 프로젝트에서 오류를보고하지 않은 몇 가지 문제를 발견했습니다.
전통적인 봄 프로젝트에는 오류가 없지만 SpringBoot 프로젝트에서는보고됩니다. Bean에 주입 된 클래스 방법이 비교적 간단한 방식으로 제공되면 SpringBoot 자체로 자동으로 구성된 일부 Bean으로 반복되며 오류 가보고되기 때문입니다.
따라서 주입 할 필요가없는 콩을 제거하십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.