티스토리 뷰

2020/05/13 - [framework/Springboot] - spring 프로젝트에서 springboot 프로젝트로 migration 하기 (1) - pom.xml

2020/05/13 - [framework/Springboot] - spring 프로젝트에서 springboot 프로젝트로 migration 하기 (2) - web.xml

 

앞서 springboot 전환을 하는데 있어서 필요한 pom.xml 변경, web.xml 변경에 대해서 살펴봤다. 이번 챕터는 springboot 전환에 따라 어떤 파일이 추가 및 변경이 되어야 하는지에 대한 기술을 하겠다. 

 


일단 가장 먼저 다뤄야할 부분은 앞서도 나왔지만 springboot 메인 클래스를 만들어야 한다.

 

Application.java

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
    	SpringApplication application = new SpringApplication(Application.class);
    	application.run(args);
    }
}

 

가장 기본적인 메인 클래스의 모습이다.

@SpringBootApplication = @SpringBootConfiguration + @ComponentScan + @EnableAutoConfiguration 

는 기억해 둘 필요가 있다. 특히 이중 @EnableAutoConfiguration은 springboot의 핵심이다. 나는 spring 설정에 비해 설정을 많이 하지도 않았는데 이녀석이 잘 돌아가는건 바로 미리 정의되어 있는 bean을 가져와서 등록시켜 주기 때문이다. 미리 정의되어 있는 bean은 어디서 볼수 있나? spring-boot-autoconfigue의 spring.factories 에서 볼수 있다. 

 

spring.factories (springboot 1.4.2 version)

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# 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.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
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.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.hornetq.HornetQAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer

# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.velocity.VelocityTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.web.JspTemplateAvailabilityProvider

수많은 클래스가 autoconfigure로 들어가있고 그 클래스 내부로 들어가보면 모두 @Configuration 이 붙어있어서 이런것들이 다 bean으로 생성된다는 것을 알수 있다. 물론 이것들이 다 bean이 되는건 아니고 @Conditional 여부에 따라 결정된다. 또한 @EnableAutoConfiguration(exclude = {xxxxx, xxxxx}) 를 통해 원치 않는 설정은 뺄수 있다. 

 

@ComponentScan 도 자동으로 들어가있는데 자동설정으로 사용하게 된다면 스캔하는 위치는 Application.java 가 위치한 패키지 기준으로 스캔한다고 보면 된다. 이부분을 주의해서 Application.java를 위치시키도록 하자. 물론 @ComponentScan을 통해 스캔하는 위치를 재정의 할수도 있다. 

 

그리고 나중에 빌드를 위해서도 Application.java 클래스의 위치는 pom.xml 의 plugin에서 지정한 위치와 일치해야 한다. 

<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    <mainClass>abc.Application</mainClass>
  </configuration>
</plugin>

application.properties (or application.yml)

 

spring project를 하고 있었다면 당연히 사용하고 있었을 파일이지만 그렇지 않은 곳도 있다. xml 로 혹은 DB로 설정 관리를 하고 있는 곳도 있는데 적어도 springboot를 사용하려면 설정관리 포인트를 application.properties (혹은 application.yml 문법만 조금 다르다.) 로 옮겨와야 한다. 기존에는 이 파일이 내가 자바 코드 내에서 써먹을 외부 환경변수와 비슷한 개념으로 사용했다면 springboot에서는 그 외에 많은 내장된 설정을 여기에서 컨트롤 할 수 있다. 그래서 매우 중요하다. application.properties 파일은 src/main/resoureces 하위 어느곳에 위치하고 있어도 된다. 필자처럼 classpath:/config/application.properties에 넣어놔도 인식이 잘 된다. 

또한 application-local.properties, application-dev.properties, application-prd.properties 처럼 spring profile 에 따라 파일을 자동으로 인식을 한다. 즉 개발서버에서 spring.profiles.active=dev 로 설정을 했으면 저중에 application-dev.properties 를 자동으로 인식을 한다는 것이다. (매우편리)

 

전환을 하며 application.properties에 간단히 설정한 내용은 다음과 같다. 

server.port=8080
server.context-path=/
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.http.encoding.charset=UTF-8
spring.http.encoding.enable=true
spring.http.encoding.force=true
spring.http.encoding.force-request=true
spring.http.encoding.force-response=true
server.tomcat.uri-encoding=UTF-8
spring.http.multipart.enabled=false
server.session.timeout=1800

설정에 의미가 다 있어서 이해하기는 어렵지 않을 것이다. 중요한건 springboot에서 권고하는 Sitemesh나 Thymeleaf를 사용하지 않고 JSP를 기본 view로 사용하기 때문에 spring.mvc.view 설정이 꼭 들어가야 한다. 

더욱 자세한 property 설명은 제일 자세히 나온 블로그인 https://pooheaven81.tistory.com/144 에서 확인하도록 하자. 


정적 자원 위치 변경

 

springboot에서는 정적자원을 읽어오는 위치는 classpath:/static, classpath:/public, classpath:/resources 이다. 

이처럼 배치를 해야 한다는 것이다. 필자는 public이라는 폴더명을 선택하여 사용하였다. 위에 나온것중 아무거나 써도 무방하다. 내가 만약 /public/images/abc.png 라는 파일을 접근하고 싶다면 localhost:8080/images/abc.png 로 접근이 가능하다. 기본 리소스 위치는 없는 것으로 취급을 하는 것이다. 이걸 변경하고 싶다면

application.properties 파일에서 spring.mvc.static-path-pattern: /public/** 으로 한다면 abc.png에 대한 접근은 localhost:8080/public/images/abc.png 로 가능하다. 

주의할점은 기본 리소스 키워드 (static, public, resources) 는 @RequestMapping 주소로 사용이 되면 안된다. 

 


무언가가 더 있었던것 같은데 생각이 나지 않는다. 망각의 주기가 빨라져가는 느낌.. 

앞서 본것과 더불어 이번 글까지 본다면 대략적인 springboot의 설정은 완료가 되었다. 세부적인건 다음 장에서 보도록 하자.

 

spring 프로젝트에서 springboot 프로젝트로 migration 하기 (1) - pom.xml

spring 프로젝트에서 springboot 프로젝트로 migration 하기 (2) - web.xml

spring 프로젝트에서 springboot 프로젝트로 migration 하기 (3) - 파일 추가 및 변경

spring 프로젝트에서 springboot 프로젝트로 migration 하기 (4) - logback

spring 프로젝트에서 springboot 프로젝트로 migration 하기 (5) - 빌드 및 실행

spring 프로젝트에서 springboot 프로젝트로 migration 하기 (6) - XML config to JAVA

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31