728x90
반응형

SpringBoot는 어플리케이션이 시작될 때 필요한 기본 설정들을 자동으로 설정하게 되어있는데, 그중에 DataSource 설정이 자동구성 될 때 필요한 데이터베이스 정보가 설정되지 않아 발생하는 문제다.

 

프로젝트가 생성될 때 appliction.properties 파일이 자동 생성되었으나 빈파일로 되어있을 것인데, 여기에 사용자가 원하는 DB 설정을 넣고, 맞는 드라이버와 라이브러리 설치, JDBC 설정을 해야한다는 의미다.

 

만약 당장 JDBC설정이 필요없고 어떤 DB를 사용할지 결정하지 않았다면 다음의 소스를 참조하면 된다.

 

스프링부트 메인 클래스에 어노테이션을 추가한다.

 

@SpringBootApplication

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

public class Application {

    public static void main(String[] args) {

          SpringApplication.run(Application.class, args);

    }

}

 

다시 실행하면 정상가동 된다.



출처: https://lemontia.tistory.com/586 [side impact]

728x90
반응형

'Web Programming > spring' 카테고리의 다른 글

Spring RestTemplate Get 요청  (0) 2018.09.05
spring resttemplate timeout  (0) 2018.09.05
@ResponseBody @RestController  (0) 2018.09.04
No mapping found for HTTP request with URI  (0) 2018.09.04
BeanCreationException  (0) 2018.09.04
728x90
반응형

스프링 RestTemplate 사용

서버에 요청을 하면 XML 형식으로 응답하는 서버와 HTTP 프로토콜을 이용해서 통신할때 스프링 RestTemplate을 이용해서 처리하는 방법 정리. 
XML로 응답하는 서버에 GET 으로 요청을 하였다.

RestTemplate

기존에 HttpClient를 이용해서 다른 서버에 Http 요청을 해서 사용했는데, 스프링 프레임워크에서 간단히 사용할 수 있게 추상화 시켜놨다. json이나 xml형태의 응답을 쉽게 객체로 바꾸어 사용할 수 있다.
없었을때는 HttpClient 라이브러리를 생성하고, 서버에 요청한 후에 응답 값을 직접 json, xml 라이브러리를 사용해서 컨버팅 했는데, RestTemplate을 이용한 후에는 그럴 필요가 없어졌다.

사용

RestTemplate 객체를 만들고, 요청하려는 URI과 응답받을 객체를 만들어서 getForObject 등의 메소드를 호출한다.

1. RestTemplate 객체 생성

  • 기본 생성
        RestTemplate restTemplate = getRestTempalte();
  • 추가로 timeout 설정을 할때
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(1000 * 60 * 5);  // 5분
        factory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(factory);

2. URI 생성

스프링에서 제공하는 UriComponentsBuilder를 이용하면 체이닝 방식으로 보기 좋게 URI를 만들 수 있다.

        URI uri = UriComponentsBuilder.newInstance().scheme("http").host("docuconv.claztec.net")
                .path("/cgi/{type}")
                .queryParam("path", file.getDownloadUrl())
                .queryParam("realname", file.getName())
                .queryParam("servicecode", file.getServiceCode())
                .queryParam("useragent", file.getUserAgent())
                .queryParam("charset", file.getCharset())
                .queryParam("format", file.getOption())
                .build().expand(file.getType())
                .encode()
                .toUri();
  • path 에 {type} 의 값은 expand() 의 매개변수와 매칭이 된다.
  • queryParam 은 요청하는 파라미터를 넣어주고, 마지막에 encode()를 해준다.
    소프트웨어 중심에 존재하는 복잡성에 도전장을 내밀다 라는 문자열은 %EC%86%8C%ED%94%84%ED%8A%B8%EC%9B%A8%EC%96%B4%20%EC%A4%91%EC%8B%AC%EC%97%90%20%EC%A1%B4%EC%9E%AC%ED%95%98%EB%8A%94%20%EB%B3%B5%EC%9E%A1%EC%84%B1%EC%97%90%20%EB%8F%84%EC%A0%84%EC%9E%A5%EC%9D%84%20%EB%82%B4%EB%B0%80%EB%8B%A4로 변한다.
  • 참고로 브라우저 콘솔창에서 자바스크립트의 decodeURI(), encodeURI()로 간단히 encode, decode 해볼 수 있다.
decodeURI('%EC%86%8C%ED%94%84%ED%8A%B8%EC%9B%A8%EC%96%B4%20%EC%A4%91%EC%8B%AC%EC%97%90%20%EC%A1%B4%EC%9E%AC%ED%95%98%EB%8A%94%20%EB%B3%B5%EC%9E%A1%EC%84%B1%EC%97%90%20%EB%8F%84%EC%A0%84%EC%9E%A5%EC%9D%84%20%EB%82%B4%EB%B0%80%EB%8B%A4')
"소프트웨어 중심에 존재하는 복잡성에 도전장을 내밀다"
encodeURI('소프트웨어 중심에 존재하는 복잡성에 도전장을 내밀다')
"%EC%86%8C%ED%94%84%ED%8A%B8%EC%9B%A8%EC%96%B4%20%EC%A4%91%EC%8B%AC%EC%97%90%20%EC%A1%B4%EC%9E%AC%ED%95%98%EB%8A%94%20%EB%B3%B5%EC%9E%A1%EC%84%B1%EC%97%90%20%EB%8F%84%EC%A0%84%EC%9E%A5%EC%9D%84%20%EB%82%B4%EB%B0%80%EB%8B%A4"
  • 마지막으로 toUri()로 URI 형태로 변환한다.

3. Object 생성

  • 응답 XML
<?xml version="1.0"?>
<result>
<code>200</code>
<url>http://docuconv.claztec.net/3/1440052137_98391fc84281414c9a33c1cda3a44c50/0.htm</url>
<msg></msg>
<loss>false</loss>
</result>
  • XML을 java 객체로 표현 XmlRootElement 아래로 XmlElement로 구조를 잡아준다. 자동으로 만드는 방법도 있지만, 불필요한게 많이 생긴다. 하나하나 해주는 방법이 더 나은 것 같다.
@XmlRootElement(name = "result")
public class Result {
    @XmlElement
    private Integer code;

    @XmlElement
    private String url;

    @XmlElement
    private String msg;

    @XmlElement
    private Boolean loss;

    public Integer getCode() {
        return code;
    }

    public String getUrl() {
        return url;
    }

    public String getMsg() {
        return msg;
    }

    public Boolean getLoss() {
        return loss;
    }
}

4. 요청

        Result result = restTemplate.getForObject(uri, Result.class);

코드

ConvertService.java

@Service
public class ConvertService {

    private RestTemplate getRestTempalte() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(1000 * 60 * 5);  // 5분
        factory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(factory);
        return restTemplate;
    }

    public Result convert(String downloadUrl) {
        RestTemplate restTemplate = getRestTempalte();
        URI uri = UriComponentsBuilder.fromHttpUrl(downloadUrl).build().toUri();
        Result result = restTemplate.getForObject(uri, Result.class);
        return result;
    }

    public Result convert(File file) throws UnsupportedEncodingException {
        RestTemplate restTemplate = getRestTempalte();
        URI uri = UriComponentsBuilder.newInstance().scheme("http").host("docuconv.claztec.net")
                .path("/cgi/{type}")
                .queryParam("path", file.getDownloadUrl())
                .queryParam("realname", file.getName())
                .queryParam("servicecode", file.getServiceCode())
                .queryParam("useragent", file.getUserAgent())
                .queryParam("charset", file.getCharset())
                .queryParam("format", file.getOption())
                .build().expand(file.getType())
                .encode()
                .toUri();
        Result result = restTemplate.getForObject(uri, Result.class);
        return result;
    }
}

ConvertServiceTest.java

    @Autowired
    private ConvertService convertService;

    @Test
    public void testConvert() throws UnsupportedEncodingException {
        File file = new File();
        file.setDownloadUrl("http://cloud.tools.com/p/file/20110619.ppt");
        file.setName("소프트웨어 중심에 존재하는 복잡성에 도전장을 내밀다");
        file.setExtension("ppt");

        Result result = convertService.convert(file);
        assertNotNull(result);
        assertThat(200, is(result.getCode()));
        log.debug("url:" + result.getUrl());
    }


728x90
반응형

'Web Programming > spring' 카테고리의 다른 글

Failed to determine a suitable driver class  (0) 2020.06.29
spring resttemplate timeout  (0) 2018.09.05
@ResponseBody @RestController  (0) 2018.09.04
No mapping found for HTTP request with URI  (0) 2018.09.04
BeanCreationException  (0) 2018.09.04
728x90
반응형

// Connection Timeout 10초, ReadTimeout 10초 설정.

private RestTemplate getRestTemplate() {
HttpComponentsClientHttpRequestFactory factory 

= new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(10*1000);
factory.setReadTimeout(10*1000);
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}


728x90
반응형

'Web Programming > spring' 카테고리의 다른 글

Failed to determine a suitable driver class  (0) 2020.06.29
Spring RestTemplate Get 요청  (0) 2018.09.05
@ResponseBody @RestController  (0) 2018.09.04
No mapping found for HTTP request with URI  (0) 2018.09.04
BeanCreationException  (0) 2018.09.04
728x90
반응형

Spring 에서 restful 하게 작성하기 위해 @Controller 내에 @ResponseBody 사용하거나 혹은 @RestController 을 사용할 수 있습니다.


스프링 MVC 프레임 워크와 REST


일반적인 Spring MVC 컨트롤러와 RESTful 웹 서비스 컨트롤러의 주요 차이점은 HTTP 응답 바디가 생성되는 방식이다. 일반적인 MVC 컨트롤러는 View 기술을 사용하지만, RESTful 웹 서비스 컨트롤러는 객체를 반환하기 만하면(!) 객체 데이터는 JSON / XML 형식의 HTTP 응답에 직접 작성되게 됩니다.


▲ 일반적인 Spring MVC 흐름



@ResponseBody 와 @RestController 두가지 차이점을 알아보기 전에 우선 스프링에서 REST하게 데이터가 송수신 되는 과정은 다음과 같다.


  1. 클라이언트에서 웹서비스에 요청을 보냄.
  2. Handler Mapping과 그 타입을 찾는 Dispatcher Servlet에 의해 요청이 가로채짐.
  3. 요청은 Controller에 의해 처리되고 응답은 Dispatcher Servlet으로 반환되고 Dispatcher Servlet은 다시 View로 보내게 됩니다.

@ResponseBody

메소드에서 @ResponseBody 어노테이션을 사용하면 Spring은 반환 값을 변환하여 HTTP Response 에 자동으로 씁니다. Controller 클래스의 각 메소드에는 @ResponseBody 어노테이션이 있어야합니다.





@RestController


Spring 4.0은 @Controller와 @ResponseBody 을 합쳐놓은것 이상의 역할을 수행하는@RestController를 추가했습니다. 컨트롤러 클래스에 @RestController 어노테이션을 작성함으로써 더 이상 @ResponseBody를 모든 요청 매핑 메소드에 추가 할 필요가 없습니다. @ResponseBody 어노테이션은 이제 기본으로 작동..!




결론


스프링을 restful하게 만들 때, 앞으로는 스프링 4.0 부터 추가된 @RestController을 활용하므로써 기존의 @ResponseBody in @Controller 방식을 벗어나 좀 더 쉽게 restful한 코드를 작성할 수 있습니다.



출처: http://highcode.tistory.com/24 [HighCode]

728x90
반응형

'Web Programming > spring' 카테고리의 다른 글

Spring RestTemplate Get 요청  (0) 2018.09.05
spring resttemplate timeout  (0) 2018.09.05
No mapping found for HTTP request with URI  (0) 2018.09.04
BeanCreationException  (0) 2018.09.04
스프링 프레임워크 (Spring Framework)란?  (0) 2018.08.29
728x90
반응형

<url-pattern>/</url-pattern>

728x90
반응형

'Web Programming > spring' 카테고리의 다른 글

spring resttemplate timeout  (0) 2018.09.05
@ResponseBody @RestController  (0) 2018.09.04
BeanCreationException  (0) 2018.09.04
스프링 프레임워크 (Spring Framework)란?  (0) 2018.08.29
Dependency Injection (의존성 주입)이란?  (0) 2018.08.29

+ Recent posts