20%
23,760원
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Spring 3.xx 이상이라면 SpringDoc 사용하세요
Spring 3 이상부터는 더 이상 Springfox가 아닌 SpringDoc으로 해야 Swagger 설정을 해줄 수 있습니다.자세한 내용은 제가 참조한 아래 레퍼런스 확인해보시면 좋을 거 같아요 https://springdoc.org/https://colabear754.tistory.com/99https://velog.io/@kjgi73k/Springboot3%EC%97%90-Swagger3%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0 아래는 참고하여 작성한 코드입니다. @Configuration public class SwaggerConfig { @Bean public OpenAPI openAPI(){ return new OpenAPI() .components(new Components()) .info(apiInfo()); } private Info apiInfo() { return new Info() .title("Springdoc 테스트") .description("Springdoc을 사용한 Swagger UI 테스트") .version("1.0.0"); } } @RestController @RequestMapping("/swagger") public class SwaggerController { @Operation(summary = "문자열 반복", description = "파라미터로 받은 문자열을 2번 반복합니다.") @Parameter(name = "str", description = "2번 반복할 문자열") @GetMapping("/returnStr") public String returnStr(@RequestParam String str) { return str + "\n" + str; } @GetMapping("/example") public String example() { return "예시 API"; } @Hidden @GetMapping("/ignore") public String ignore() { return "무시되는 API"; } } NOTE:springdoc.swagger-ui.path에서 swagger url 기본 경로를 설정합니다. 저는 아래와 같이 /swagger로 접속하게끔 했습니다.# SPRINGDOC springdoc.packages-to-scan=com.example.dateanu.rest_api springdoc.default-consumes-media-type= application/json;charset=UTF-8 springdoc.default-produces-media-type= application/json;charset=UTF-8 springdoc.swagger-ui.path=/swagger springdoc.swagger-ui.disable-swagger-default-url=true springdoc.swagger-ui.display-request-duration=true springdoc.swagger-ui.operations-sorter=alpha
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Cannot resolve symbol 'EntityModel' (+ RepresentationModel)
두 가지 질문이 있습니다.EntityModel을 찾을 수 없다고 나오는데 도움을 받을 수 있을까요?? 공식문서에는 RepresentationModel를 상속하여 기능을 추가하라고 가이드하고 있는데, EntityModel와 다른가요? 1. cannot resolve symbol 'EntityModel'제 코드와 설정은 아래와 같습니다.build.gradleplugins { id 'java' id 'org.springframework.boot' version '3.0.0' id 'io.spring.dependency-management' version '1.1.0' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' repositories { mavenCentral() } dependencies { // web 라이브러리 implementation 'org.springframework.boot:spring-boot-starter-web' // JPA implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // JDBC implementation 'org.springframework.boot:spring-boot-starter-jdbc' // 타임리프 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' // TEST testImplementation 'org.springframework.boot:spring-boot-starter-test' developmentOnly 'org.springframework.boot:spring-boot-devtools' // VALIDATION implementation 'org.springframework.boot:spring-boot-starter-validation' // 롬복 compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' } tasks.named('test') { useJUnitPlatform() }pom.xml<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.1.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>dateanu</artifactId> <version>0.0.1-SNAPSHOT</version> <name>dateanu</name> <description>dateanu</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.4.4</version> </plugin> </plugins> </build> </project> application.properties# DATABASE spring.h2.console.enabled=true spring.h2.console.path=/h2-console # spring.datasource.url=jdbc:h2:~/local spring.datasource.url=jdbc:h2:~/local;AUTO_SERVER=true spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= # PORT server.port=9090 # JPA spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect # USE THIS spring.jpa.hibernate.ddl-auto=create # spring.jpa.hibernate.ddl-auto=update // OR THIS # AVOID THIS # spring.jpa.hibernate.ddl-auto=create # spring.jpa.hibernate.ddl-auto=create-drop spring.messages.basename=messages spring.messages.fallback-to-system-locale=false Controllerpackage com.example.dateanu.rest_api; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @RestController @RequiredArgsConstructor public class UserController { private final UserDaoService service; // 싱글톤 객체를 생성자주입을 하기 위해 꼭 final이 붙어야한다. @GetMapping("/users") public List<User> retrieveAllUsers() { return service.findAll(); } // GET /users/1 @GetMapping("/users/{id}") public User retrieveUser(@PathVariable int id) { User user = service.findOne(id); if(user == null){ throw new UserNotFoundException(String.format("ID[%s] not found",id)); } // HATEOAS return user; } @PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user){ User savedUser = service.save(user); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } @DeleteMapping("/users/{id}") public ResponseEntity<User> deleteUser(@PathVariable int id){ User user = service.deleteById(id); if(user == null){ throw new UserNotFoundException(String.format("ID[%s] not found")); } return new ResponseEntity<>(user, HttpStatus.OK); } @PutMapping("/users/{id}") public ResponseEntity<User> replaceUser(@PathVariable int id,@RequestBody User user){ User replacedUser = service.replace(id,user); return new ResponseEntity<>(replacedUser, HttpStatus.OK); } @PatchMapping("/users/{id}") public ResponseEntity<User> updateUser(@PathVariable int id,@RequestBody User user){ User updatedUser = service.update(id,user); return new ResponseEntity<>(updatedUser, HttpStatus.OK); } } 어떤 것 때문인지 몇 시간을 구글링하고 디버깅해봐도 해결되지가 않네요 ㅠㅠ** 2.4.4 version에 hateoas 의존성 추가했으며, Gradle, Maven 모두 refresh 하였습니다.2.공식문서에서는 RepresentationModel 을 상속받아 쓰게끔 가이드가 되어있는 것을 확인했습니다.https://spring.io/guides/gs/rest-hateoas/EntityModel을 사용하는 것과 다른 것인지, 어떤 것이 best practice 인지 알려주실 수 있나요??** 이 또한 cannot resolve symbol 'representationmodel' 에러가 발생하네요 ㅠㅠ 감사합니다 :-)
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
테이블 찾을 수 없음
참고로 user테이블이 이미 다른 database에서 사용중인것 같아서 user_table로 이름 지정했습니다. 테이블은 잘 만들어졌습니다.그런데data.sql에 해당 Unable to resolve table 'user_table' 문구를 가진 빨간 전구 user_table에 빨간 불이 들어옵니다.insert into user_table values (1, sysdate(), 'User1', 'test1111', '701010-1111111'); insert into user_table values (2, sysdate(), 'User2', 'test2222', '801010-1111111'); insert into user_table values (3, sysdate(), 'User3', 'test3333', '901010-1111111'); @Entity @Table(name = "user_table") public class User { @Id @GeneratedValue private Integer id; @Size(min = 2, message = "Name은 2글자 이상 입력해 주세요!") @ApiModelProperty(notes = "사용자 이름을 입력해 주세요.") private String name; @Past @ApiModelProperty(notes = "사용자 등록일을 입력해 주세요.") private Date joinDate; @ApiModelProperty(notes = "사용자 패스워드를 입력해 주세요.") private String password; @ApiModelProperty(notes = "사용자 주민번호를 입력해 주세요.") private String ssn; }spring: messages: basename: messages mvc: pathmatch: matching-strategy: ant_path_matcher datasource: url: jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false jpa: show-sql: true hibernate: ddl-auto: create-drop h2: console: enabled: true path: "/h2-console".yml 파일에도 대소문자 무시도 추가해 보았지만 여전히 실행시 이런 에러가 발생하고요Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/D:/intelliJavaPractice/restful-web-service/target/classes/data.sql]: insert into user_table values (1, sysdate(), 'User1', 'test1111', '701010-1111111'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user_table" not found (this database is empty); SQL statement:Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user_table" not found (this database is empty); SQL statement:어떻게 해야 해결이 될까요. 도움주시면 정말 감사하겠습니다.
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
hateoas entityModel이 import가 안됩니다
동영상을 보고 따라서 pom.xml에 hateoas 추가했지만 usercontroller에 entityModel이 import되지 않습니다. spring boot 버전은 2.7.8인데 pom.xml에 다른걸 더 작성해야하나요?
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
9:08쯤 생성자 오류 부분
9:08쯤 생성자 오류 부분이 왜 발생하나요??이미 post 필드 외 필드들에 대한 생성자는 annotation에 의해 생성되어 있는데 갑자기 왜 오류가 발생하는지 이해가 되지 않습니다..
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
WebSecurityConfigurerAdapter deprecated 해결
@Bean public UserDetailsService userDetailsManager(BCryptPasswordEncoder bCryptPasswordEncoder){ InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withUsername("user") .password(bCryptPasswordEncoder.encode("userPass")) .roles("user") .build()); manager.createUser(User.withUsername("admin") .password(bCryptPasswordEncoder.encode("adminPass")) .roles("user", "admin") .build()); return manager; } @Bean public BCryptPasswordEncoder encodePassword(){ return new BCryptPasswordEncoder(); }
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Actuator dependency and Swagger Stater 3.0.0 충돌 에러 해결
아래 블로그 참고해주세요. 저는 이걸로 해결했습니다.https://dkswnkk.tistory.com/672
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
JPA 강의 - delete 구현시 에러 발생합니다.
안녕하세요.강의 잘 듣고 있습니다.현재 JPA 강의 - delete 부분을 수강 중입니다.그런데, 컨트롤러에 아래 코드 추가 후 response에 403 에러 (foobidden) 이 출력됩니다.security에 아래 코드처럼 설정해 줬는데도 에러가 나니, 이유를 모르겠습니다. ;;;;@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests((auth) -> { auth.antMatchers("/jpa/users").permitAll(); }); return http.build(); }@DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id) { userRepository.deleteById(id); }
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Springboot 3.X 버전이신분 Swagger 오류 해결
Springfox 말고 Springdoc로 하면 됩니다.Springfox는 2.7.X 버전에서만 작동돼서 3.0이상부터는 Springdoc을 사용해야합니다ㅓ.porm.xml - Dependency <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.9</version> </dependency>SwaggerConfig Class@Configuration //@EnableSwagger2 @OpenAPIDefinition public class SwaggerConfig { @Bean public OpenAPI api(){ Info info = new Info().title("").version("v3").description("aaa"); return new OpenAPI().components(new Components()).info(info); } }
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
헤티오스 빈 문제
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed 현재 스프링부트 2.7.9쓰고있고 어떻게 해결해야할까요
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
ResponseEntity created
return ResponseEntity.created(URI.create("/Member/"+id)).build(); 이렇게 코드 이동을 시켰느데 Header에 Location의 경로에는 이동하고 싶은 URI가 있지만 화면은 빈 화면을 보여줍니다. 어떻게 이동할 수 있나요?? 선생님께서 작성하신대로해도 Header의 Location의 경로은 저렇게 있지만 실행하면 빈 화면만나옵니다. 원하는 메시지와 함께 이동을 원할 시 어떻게 해야 할까요?
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
스프링 2.7.8 swagger 오류 해결법
pom.xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> application.ymlspring: mvc: pathmatch: matching-strategy: ant_path_matcher messages: basename: messages
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
User 의 List<Post> posts 컬렉션 조회시
안녕하세요. JPA 로 Post 를 등록하고 User 의 List<Post> posts 컬렉션 정보를 조회할때 질문드립니다.post 등록시 User 의 List<Post> posts 컬렉션에 따로 post 를 넣지 않았는데 조회할 경우에 post 정보가 나오게되는 이유가 궁금합니다.... post가 User 컬렉션에 자동적으로 저장되는 것인가요?
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
@Size(min, max) 검증 관련 질문
안녕하세요.User 테이블에 데이터를 삽입하다 검증 애노테이션이 적용이 안되서 질문드립니다. 동일한 질문이 있어서 Javax.validation 의존성 삭제하고 springboot.starter validation 을 적용했지만 계속 검증이 안되는 상황입니다.@Size(min=2, max=4)private String name;이름 필드에 제한을 두었는데 max 테스트는 에러를 내보내지만 min 을 테스트했을때 한글자 문자를 넣었을 때 왜 에러가 발생되지 않는지 궁금합니다..
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
swagger 3 질문입니다.(Step 24)
안녕하세요 springboot 3에서는 swagger 2를 이용할 수 없더라구요.( 추가로 강의자료에서 제공해주신 springfox3 버전을 이용해도 index.html에 접속이 되질 않아 springdoc으로 진행하는 상황입니다.)그래서 springdoc, swagger3를 사용하여 http://localhost:8088/swagger-ui/index.html로 들어가 실습을 진행하고 있습니다.강의자료를 참고하여 springfox형식을 springdoc에 맞춰 작성하여 info, contact,license 까지 확인할 수 있었습니다. 그런데 produce,consume 부분을 구현하지 못했는데 springdoc에서는 produce,consume이 없어진건가요? 아니면 다른 방법이 있을까요? 강의자료는 springfox 기준이라서 아직 produce, consume 부분을 해결하지 못한 상태입니다.package com.example.restfulwebservice.config; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Contact; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @Configuration public class SwaggerConfig { private static final Contact CONTACT = new Contact().name("Kenneth Lee") .url("http://www.joneculsting.co.kr") .email("edowon@joneconsluting.co.kr"); private static final License LICENSE= new License().name("Apache 2.0") .url("http://www.apache.org/licenses/LICENSE-2.0"); private static final Info INFO = new Info().title("Awesome API Title") .contact(CONTACT) .description("Awesome API Documentation") .version("1.0") .license(LICENSE) .termsOfService("urn:tos"); private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES = new HashSet<>(Arrays.asList("application/json", "application/xml")); @Bean public OpenAPI springShopOpenAPI() { return new OpenAPI().info(INFO).; } }
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
spring initializr를 설치해도 뜨질 않습니다.
inteillj communiuty로 사용하면 spring initializr을 직접 다운 받아야 한다고 해서 강의랑 똑같이 설정하고 다운받았는데도 new project에 spring initializr가 안뜹니다...
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
insert 문제
질문에 defer-datasource-initialization: true 추가하라해서 했는데도 안됩니다
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
json 질문
{"hey":"guy","anumber":243, "anobject":{"whoa":"nuts","anarray":[1,2,"thr<h1>ee"],"more":"stuff"}, "awesome":true,"bogus":false,"meaning":null,"japanese":"明日がある。","link":"http://jsonview.com","notLink":"http://jsonview.com is great"}json안에 json 으로 데이터를 보낼려면 어떻게 해야하나요?
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
db connect 안됨
security부분 건너뛰고 jpa부분 부터 하고있는데 db connect 부분이 오류나서 ,yml에 datasource: hikari: jdbc-url: jdbc:h2:mem:testdb username: sa하니 연결은 되었는데 실해하니까 create table이 만들어지지 않고org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table if exists user cascade " via JDBC Statement at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:419) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:403) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:272) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:178) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:149) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:117) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:242) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final] at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:143) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]오류가 뜹니다.
- 미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
swagger 오류
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>pom.xml에 swagger관련 추가시There are test failures. Please refer to C:\Users\Owner\Desktop\RESTJPA\restjpa\target\surefire-reports for the individual test results. Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream. 이런 오류가 나고또다른dependency에 원래 코드로 작성하면<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency> http://localhost:8080/v2/api-docs로 접속하면java.lang.TypeNotPresentException: Type javax.servlet.http.HttpServletRequest not present오류가 뜹니다. 현재 버전 바뀌면서javax ->jakarta로 변경된것 같은데 어떻게 해결하나요?