패스트 캠퍼스 JAVA 웹 프로그래밍 마스터 23일차(Spring Boot, HTTP, 배포 설정, Message Converter)
lalwr
...분 소요
- 로컬과 배포시 설정
- 로컬에서는 메모리 DB를 사용하다가 배포시에는 DB설정을 변경 하여야한다.
- Spring Profile(스프링 자체 기능)
- 로컬, 개발, 운영 설정을 jar로 다 가지고 다닌다. 어디서든 한번에 환경에 맞게 배포를 할 수 있다.
- 스프링 말고 다른언어가 있으면 에서는 배포에 대한 설정을 더 해야한다.
- 빌드도구 툴
- 디렉토리별로 설정파일을 만든다. 로컬, 개발, 운영에 한번에 배포하려면 3번에 걸쳐 각각 해야한다.
- VM option
- 자바로 실행할때 옵션
- java VM옵션 Helloworld 프로그램옵션
- HTTP 데이터 통신
- 브라우저에서 post로 값을 보낼때 header에 담아서 보낸다.
- 브라우저에서 body에 JSON,xml등 다양한 형식으로 값을 담아서 보낼수 있다.
- WEB API에서 DTO같은 객체에 담고 싶을때 Spring mvc 에서 spring message converter를 통해 처리할 수 있다. 요청이 올때와 응답할때 처리 해준다.
- @RestController를 선언하면 body에 담아서 응답한다.
- Form에서 submit하면 FormData형태로 값을 보낸다.
- Spring Boot에서 배포관련 설정
- Profile설정에 따라 다른 객체를 주입할 수 있다.
- application.yml 파일에 다음과 같이 기본으로 사용할 profile을 설정할 수 있다.
spring:
profiles:
active: local
my:
address: 192.168.1.100 <----- 공통설정
---
spring:
profiles: local
my:
address: 127.0.0.1 <---- local
---
spring:
profiles: real
my:
address: 192.168.1.120 <---- real
@Controller
@RequestMapping("/boards")
public class BoardController {
@Value("${my.address}")
private String address;
}
java -jar 스프링부트애플리케이션.jar --spring.profiles.active=real
package examples.boot.simpleboard.service;
public interface MyService {
public String getName();
}
ckage examples.boot.simpleboard.service.impl;
import examples.boot.simpleboard.service.MyService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("real")
public class RealServiceImpl implements MyService {
@Override
public String getName() {
return "real";
}
}
package examples.boot.simpleboard.service.impl;
import examples.boot.simpleboard.service.MyService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("local")
public class MyServiceImpl implements MyService {
@Override
public String getName() {
return "local";
}
}
@Autowired
MyService myService;
- Spring boot 2.0
- @EnableWebMvc 을 선언 안해줘도 된다. 선언 안해주면 기본으로 사용하는 메시지 컨버터를 사용한다.
- @EnableWebMvc 을 선언하면 메시지 컨버터를 설정 해줘야한다.
- spring boot는 의존성을 추가하면 자동으로 설정이 된다. 웹 프로그래밍과 관련된 내용들이 자동으로 설정된다. 기본적인 메시지 컨버터들도 자동으로 등록된다.
- Hibernate
- 엔티티를 선언하면 Hibernate가 해당 엔티티를 상속하여 프록시 객체를 만들어 오버라이딩 하여 사용한다.
- Message Converter
- spring 을 이용해서 메시지 컨버터를 등록하는 방법
http://www.baeldung.com/spring-httpmessageconverter-rest - spring boot에서의 메시지 컨버터 설정
- java config파일 중 WebMvcConfigurer를 구현하는 클래스에서 다음의 메소드를 오버라이딩한다.
- converters 에 메시지를 컨버터를 등록하면 됩니다.
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
- Spring Boot 2.0에서 hibernate 5를 사용하고 엔티티를 반환하면 Exception이 발생한다. 기존의 컨버터가 변환을 못한다.
- 아래와 같이 컨버터를 생성한다
- 변환하기 위해 jackson이 제공하는 하이버네이트 모듈을 추가한다.
- 이렇게 했을 경우 LocalDateTime이 jsr310형식으로 출력되지 않는다.
- jackson이 제공하는 jsr310모듈을 추가한다.
// https://stackoverflow.com/questions/28862483/spring-and-jackson-how-to-disable-fail-on-empty-beans-through-responsebody
// https://github.com/FasterXML/jackson-datatype-hibernate/issues/87
// https://stackoverflow.com/questions/33727017/configure-jackson-to-omit-lazy-loading-attributes-in-spring-boot
@Override
public void configureMessageConverters(List> converters) {
// http://jsonobject.tistory.com/235 iso8601 형식으로 날짜 정보 출력하기
ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).modules(new JavaTimeModule()).build();
mapper.registerModule(new Hibernate5Module());
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MappingJackson2HttpMessageConverter converter =
new MappingJackson2HttpMessageConverter(mapper);
converter.setPrettyPrint(true);
converters.add(converter);
}
- ResponseEntity
- HttpStatus 상태값 알맞게 사용하기
- spring boot로 spring mvc 웹 프로그래밍을 하려면 다음의 라이브러리 의존성을 추가하면 됩니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- Spring boot JPA 구성
- Spring boot에서는 자동으로 필터가 추가되어있다.
- 필터 - Controller - service -Repository
- 크롬에서 네트워크 이력 남기기
- 개발자 도구에서 Preserve log를 체크한다
- 공부해보기
- error handling
- spring validation
- osvi(JPA관련)
- Scouter(성능 모니터링 툴)
- Gatling 툴(네트워크 트래픽 공격)
- OpenEntityManagerInViewFilter(OSIV)
이전글
...
다음글
...