신변잡기 분석 및 설계

블로그 이미지

큐그

IT 관련 및 신변잡기에 대한 포스팅을 해보고자 하는 블로그입니다.

'분류 전체보기'에 해당되는 글 65건

제목 날짜
  • 어려운 네트워크에 대해 공부해보자 2025.02.04
  • ngrinder를 이용한 성능 테스트 2024.09.18
  • nvalidDataAccessApiUsageException: Executing an update/delete query 오류 2024.07.22
  • kotlin에서 queryDSL 사용하기1 2024.07.05
  • XML -> JAVA Class 매핑 시 발생한 에러 2024.05.09
  • ByteArray -> human readable string 2024.04.29
  • Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine suitable jdbc url - spring boot 3 datasource 설정1 2024.04.28
  • @Transactional 어노테이션에 대한 정리 2023.11.26
  • Spring Security 환경에서 h2 console enabled : true일 때 오류 2023.09.10
  • 오류: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/reactivestreams/Publisher 2023.03.09

어려운 네트워크에 대해 공부해보자

IT 개발/개념 정리 2025. 2. 4. 17:01

https://abc/swagger-ui.html 환경을 그대로 복사해서 만든 abc3서버가 있다.

 

https://abc3/swagger-ui.html도 동일하게 접속했으나 아래와 같은 오류가 발생하였고 

 

결론부터 말하자면 내 경우엔 도메인 설정을 하지 않아서였다.

 

postman을 통해 도메인만 다른 API를 호출했을 때 abc는 정상적으로 처리했지만 abc3는 /api/v1/company/info  는 The requested URL was not found on this server 오류를 리턴하면서 정상적으로 호출하지 못 했다.

 

설마 도메인이 설정 안 되어있지 않을거라 생각하지 못 해서 조금 헤매게됐다.

 

해당 서버에 접속해서  curl을 이용해서 호출하려는 API가 정상 호출되는지 확인해본다. http://localhost:8080/api/v1/abc/info?customer=00000

 

curl로 호출했을 때 로그상에 무언가가 남는다면 정상적으로 호출된 것이다. curl로 호출 시에도 로그에 남는게 없다면 정상적인 API를 호출하고 있는지 확인해봐야한다.

 

curl -d "key1=value1" \ -H "Content-Type: application/x-www-form-urlencoded" \ -X POST http://localhost:8000/api/v1/abc

 

postman을 호출할 때 오류가 발생할 때 눈치를 챘어야했는데.. 이럴 경우엔 알고 있는 public ip 또는 해당 서버에 접속해서 ifconfig를 통해 ip를 확인한 후 도메인을 ip로 변경해서 호출해보자. http://ip:8080/을 endpoint로 두면 된다.

 

 

 

 

 

1dfs

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 개념 정리' 카테고리의 다른 글

ngrinder를 이용한 성능 테스트  (0) 2024.09.18
kotlin에서 queryDSL 사용하기  (1) 2024.07.05
ByteArray -> human readable string  (0) 2024.04.29
@Transactional 어노테이션에 대한 정리  (0) 2023.11.26
Spring Security 환경에서 h2 console enabled : true일 때 오류  (0) 2023.09.10
Posted by UIJ

ngrinder를 이용한 성능 테스트

IT 개발/개념 정리 2024. 9. 18. 16:00

ngrinder는 현재 java 11 버전까지 지원하기 때문에 최대 11버전으로 맞춰줘야한다.

 

java -version으로 조회했을 때 11이 아닌 상위버전으로 나오면 아래의 명령어들로 11버전으로 맞춰야한다.

 

 

vim ~/.bash_profile 파일 안에

JAVA_HOME=/usr/libexec/java_home -v 11.0.19
PATH=$PATH:$JAVA_HOME/bin
export JAVA_HOME
export PATH

 

bash_profile은 일시적으로 변경하는 방법이라 영구적으로 변경하려면 ~/.zshrc를 수정해야한다.

 

export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.19)
export PATH=$PATH:$JAVA_HOME/bin

추가 후 

source ~/.zshrc 적용

 

최신 버전의 ngrinder를 다운받는다.

 

https://github.com/naver/ngrinder/releases/download/ngrinder-3.5.9-p1-20240613/ngrinder-controller-3.5.9-p1.war

 

다운받은 ngrinder를 적당한 파일 경로에 위치시켜주고 /Users/user/ngrinder 파일에 위치시켜줬다.

 

 java -Djava.io.tmpdir=${NGRINDER_HOME}/.ngrinder/lib -jar ngrinder-controller-3.5.9-p1.war --port 7070 명령어를 실행시켜 ngrinder를 실행시킨다.

 

ngrinder를 실행시킨 후 script를 작성하려할 때 계속되는

 

ERROR FileEntryRepository.java:192 : Error while fetching files from SVN for admin 오류로 인해.. 원인은 알 수 없고 곤란했는데 아래 url처럼 삭제했다가 다시 지우니깐 됐다.(근데 이것도 2차례 정도 지우니깐 그제서야.. 제대로 작동함. 안 되면 여러번 삭제했다가 다시 시도해볼 것)

 

https://github.com/naver/ngrinder/discussions/968

 

 

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 개념 정리' 카테고리의 다른 글

어려운 네트워크에 대해 공부해보자  (0) 2025.02.04
kotlin에서 queryDSL 사용하기  (1) 2024.07.05
ByteArray -> human readable string  (0) 2024.04.29
@Transactional 어노테이션에 대한 정리  (0) 2023.11.26
Spring Security 환경에서 h2 console enabled : true일 때 오류  (0) 2023.09.10
Posted by UIJ

nvalidDataAccessApiUsageException: Executing an update/delete query 오류

IT 개발/에러 2024. 7. 22. 19:43

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query] with root cause

jakarta.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:517) ~[hibernate-core-6.4.4.Final.jar:6.4.4.Final]
at org.hibernate.query.sqm.internal.QuerySqmImpl.executeUpdate(QuerySqmImpl.java:671) ~[hibernate-core-6.4.4.Final.jar:6.4.4.Final]
at cohttp://m.querydsl.jpa.impl.JPAUpdateClause.execute(JPAUpdateClause.java:76) ~[querydsl-jpa-5.1.0-jakarta.jar:na]

 

위와 같은 오류가 발생했을 때 transaction이 없어서 발생하는 오류로 update queryDSL에 @Transactional 선언을 하면 해결된다.

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 에러' 카테고리의 다른 글

XML -> JAVA Class 매핑 시 발생한 에러  (0) 2024.05.09
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine suitable jdbc url - spring boot 3 datasource 설정  (1) 2024.04.28
오류: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/reactivestreams/Publisher  (0) 2023.03.09
오류: java.lang.ArithmeticException: Rounding needed with the rounding mode being set to RoundingMode.UNNECESSARY  (0) 2023.03.09
오류:org.springframework.dao.InvalidDataAccessApiUsageException: For input string: "XXX"; nested exception is java.lang.NumberFormatException: For input string: "XXX"  (0) 2023.03.08
Posted by UIJ

kotlin에서 queryDSL 사용하기

IT 개발/개념 정리 2024. 7. 5. 19:13
 implementation("com.querydsl:querydsl-jpa:5.0.0:jakarta")
 implementation("com.querydsl:querydsl-apt:5.0.0:jakarta")

build.gradle.kts 파일에 아래 내용을 추가해준다.

 

plugins {
	kotlin("kapt") version "1.9.23"
}

dependencies {
    // querydsl
    implementation("com.querydsl:querydsl-jpa:5.1.0:jakarta")
    implementation("com.querydsl:querydsl-apt:5.1.0:jakarta")
    kapt("com.querydsl:querydsl-apt:5.1.0:jakarta")
    kapt("org.springframework.boot:spring-boot-configuration-processor")

    implementation("org.hibernate:hibernate-core:6.1.0.Final")

}

 

kapt 플러그인을 추가해 kotlin에서도 querydsl을 사용할 수 있게 해준다.

 

gradle clean 후 build를 해주면 build > classes > generated > source > kapt 경로에 Q클래스들이 생성된다. 

 

springboot3으로 버전이 올라가면서 jdk는 17 버전을 선택하게 됨. 17버전부터는 javax -> jakarta 패키지로 변경되어 의존성 추가 시 뒤에 classifier에 jakarta를 표기해야함.

 implementation("com.querydsl:querydsl-jpa:5.0.0:jakarta")
 implementation("com.querydsl:querydsl-apt:5.0.0:jakarta")

 

 

kotlin + queryDSL를 사용해서 개발하던 중 아래와 같은 오류를 마주함.

and token 'SEPARATOR', no viable alternative at input 'select table_a.cstCd, table_a.cstNm, table_a.orderNo, group_concat(table_a.goodsSno *SEPARATOR '|')'
from shopOrder shopOrder

 

mysql에서 사용하던 group_concat 함수를 아래와 같이 등록하여 사용하던 중에 group_concat의 기본 separator가 콤마라서 |로 바꾸려고 하는 중에 separator는 사용할 수 없는 명령어라는 오류 발생 여러가지 방법으로 시도하려고 했으나.. 해결되지 않아 어쩔 수 없이 자바단에 함수를 생성하여 replace하는 것으로 변경

 

override fun contributeFunctions(functionContributions: FunctionContributions) {
    functionContributions.functionRegistry.register("GROUP_CONCAT", StandardSQLFunction(
        "group_concat",
        StandardBasicTypes.STRING
    ))
}

 

mysql의 group_concat을 querydsl에서 사용하려면 함수를 등록해야 사용할 수 있다. 그렇지 않으면 아래와 같은 에러 발생

2024-07-03T14:41:55.736+09:00 ERROR 54176 --- [nio-1899-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode 
 \-[METHOD_CALL] MethodNode: '('
    +-[METHOD_NAME] IdentNode: 'group_concat' {originalText=group_concat}
    \-[EXPR_LIST] SqlNode: 'exprList'
       \-[DOT] DotNode: 'or0_.goods_sno' {propertyName=goodsSno,dereferenceType=PRIMITIVE,getPropertyPath=goodsSno,path=Ord.goodsSno,tableAlias=or0_,className=com.xxxx.orderapi.domain.order.entity.Ord,classAlias=Ord}
          +-[ALIAS_REF] IdentNode: 'or0_.order_no, or0_.goods_sno' {alias=ord, className=com.xxxxx.orderapi.domain.order.entity.ord, tableAlias=or0_}
          \-[IDENT] IdentNode: 'gdmGoodsSno' {originalText=gdmGoodsSno}
 [select ord.cstCd, ord.orderNo, ord.invoiceNo, ord.invoiceCompanySno, group_concat(ord.goodsSno)
from com.xxxxx.rderapi.domain.order.entity.Ord ord]] with root cause

 

아래처럼 DBDiaclect을 extends한 후 function을 추가하여 group_concat을 사용할 수 있도록 등록함.


class CustomMySQLDialect: MariaDBDialect() {

    override fun contributeFunctions(functionContributions: FunctionContributions) {
        functionContributions.functionRegistry.register("GROUP_CONCAT", StandardSQLFunction(
            "group_concat",
            StandardBasicTypes.STRING
        ))
    }
}

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 개념 정리' 카테고리의 다른 글

어려운 네트워크에 대해 공부해보자  (0) 2025.02.04
ngrinder를 이용한 성능 테스트  (0) 2024.09.18
ByteArray -> human readable string  (0) 2024.04.29
@Transactional 어노테이션에 대한 정리  (0) 2023.11.26
Spring Security 환경에서 h2 console enabled : true일 때 오류  (0) 2023.09.10
Posted by UIJ

XML -> JAVA Class 매핑 시 발생한 에러

IT 개발/에러 2024. 5. 9. 13:33
No validator could be found for constraint 'jakarta.validation.constraints.NotEmpty' validating type

@NotEmpty를 이용해서 validation check를 하고 있었는데 empty의 경우 컬렉션 또는 문자열 타입만 사용할 수 있다.

 

객체에 @NotEmpty를 사용해서 에러 발생 -> @NotNull로 변경

 

 

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "totalMemberBankDcPrice" (class com.fassto.godomallorderapi.domain.order.dto.response.godomall.GodomallOrderResponse), not marked as ignorable (63 known properties: "depositor", "totalCouponOrderDcPrice", "orderGoodsNm", "memGroupNm", "totalCouponDeliveryDcPrice", "orderTypeFl", "realTaxFreePrice", "orderIp", "useDeposit", "orderDate", "orderGoodsCnt", "orderInfoDataList", "pushCode", "totalDeliveryCharge", "realTaxSupplyPrice", "orderNo", "orderGoodsDataList", "apiOrderNo", "paymentDt", "totalGoodsDcPrice", "totalMyappDcPrice", "idx", "settlePrice", "mallSno", "useMileage", "totalDeliveryInsuranceFee", "overseasSettlePrice", "memId", "taxFreePrice", "accountNumber", "addField", "orderStatus", "totalMemberOverlapDcPrice", "orderGoodsNmStandard", "appOs", "totalMileage", "bankName", "orderDeliveryDataList", "taxVatPrice", "totalMemberMileage", "realTaxVatPrice", "orderEmail", "taxSupplyPrice", "orderGoodsData", "overseasSettleCurrency", "memNo", "totalGoodsPrice", "totalGoodsMileage", "giftData", "orderChannelFl", "totalCouponGoodsDcPrice", "statisticsAppOrderCntFl", "totalMemberDcPrice", "giftDataList", "firstSaleFl", "totalCouponGoodsMileage" [truncated]])
 at [Source: (StringReader); line: 231, column: 14] (through reference chain: com.fassto.godomallorderapi.domain.order.dto.response.godomall.OrderReturnRoot["return"]->com.fassto.godomallorderapi.domain.order.dto.response.godomall.OrderSearchResponse["order_data"]->java.util.ArrayList[0]->com.fassto.godomallorderapi.domain.order.dto.response.godomall.GodomallOrderResponse["totalMemberBankDcPrice"])
	at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61) ~[jackson-databind-2.17.1.jar:2.17.1]

 

JSON에는 totalMemberBankDcPrice 값이 존재하지만 매핑 대상이 되는 Class에 해당 field가 존재 하지 않아서 데이터를 맵핑시키지 못해 발생하는 현상

 

=> Class에 @JsonIgnoreProperties(ignoreUnkown = true)를 추가하여 매핑되지 않는 값은 무시하도록 설정

 

java.io.NotSerializableException: com.fassto.godomallorderapi.domain.order.dto.response.godomall.OrderGoodsData

java.io.NotSerializableException: com.fassto.godomallorderapi.domain.order.dto.response.godomall.OrderGoodsData


Serializable을 implement 상속하지 않아서 발생한 오류

 

[PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.fassto.godomallorderapi.domain.order.entity.GodomallOrd column: gdm_goods_no (should be mapped with insert="false" update="false")

 

복사를 통해 속성값 추가하다가 @Columns(name="gdm_goods_no")도 동일하게 추가해서 동일한 컬럼명이 존재해서 발생한 오류

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 에러' 카테고리의 다른 글

nvalidDataAccessApiUsageException: Executing an update/delete query 오류  (0) 2024.07.22
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine suitable jdbc url - spring boot 3 datasource 설정  (1) 2024.04.28
오류: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/reactivestreams/Publisher  (0) 2023.03.09
오류: java.lang.ArithmeticException: Rounding needed with the rounding mode being set to RoundingMode.UNNECESSARY  (0) 2023.03.09
오류:org.springframework.dao.InvalidDataAccessApiUsageException: For input string: "XXX"; nested exception is java.lang.NumberFormatException: For input string: "XXX"  (0) 2023.03.08
Posted by UIJ

ByteArray -> human readable string

IT 개발/개념 정리 2024. 4. 29. 09:55

 

ByteArray.toString()를 하니 당연히 byteArray의 주소값이 출력된다. 

 

1. toString() 호출 시 charset를 인자로 넘겨준다.

 

val bytes = "Hi".toByteArray()
val bytesToString = bytes.toString(Charset.defaultCharset())

=> Prints: "Hi" not bytearray ID "[B@9a7d34b"

 

2. String 생성자의 인자로 넘겨준다.

 

val bytes = "Hi".toByteArray()
val bytesToString = String(bytes)

=> Prints: "Hi" not bytearray ID "[B@9a7d34b"
반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 개념 정리' 카테고리의 다른 글

ngrinder를 이용한 성능 테스트  (0) 2024.09.18
kotlin에서 queryDSL 사용하기  (1) 2024.07.05
@Transactional 어노테이션에 대한 정리  (0) 2023.11.26
Spring Security 환경에서 h2 console enabled : true일 때 오류  (0) 2023.09.10
[아이템 61] 박싱된 기본 타입보다는 기본 타입을 사용하라  (0) 2022.08.15
Posted by UIJ

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine suitable jdbc url - spring boot 3 datasource 설정

IT 개발/에러 2024. 4. 28. 16:38

신규 프로젝트를 진행하는데 

Spring Boot 2 -> 3으로 변경하면서 JAVA 17버전으로 올리는 것도 진행했다.

기존 프로젝트의 설정을 그대로 사용하지 않고 새로 set up을 했는데 그 과정에서 별 것도 아닌데 많은 오류를 만나게 되었다.

 

 

이전엔 아래와 같이 작업했는데 

 

오류 - 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine suitable jdbc url

spring:
  datasource:
    hikari:
      jdbc-url: jdbc:log4jdbc:mariadb:/localhost:3306
      username: 
      password: 
      driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
      maximum-pool-size: 4
      minimum-idle: 1
      connection-timeout: 60000
      max-lifetime: 60000

 

Spring 2.7.2 버전

 

spring:
  datasource:
    url: 
    username: 
    password:
    driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
    hikari:
      maximum-pool-size: 4
      minimum-idle: 1
      connection-timeout: 60000
      max-lifetime: 60000

 

Spring 3.2.5 버전

@Bean
@ConfigurationProperties(prefix = "spring.datasource")
fun dataSourceProperties(): DataSourceProperties {
    return DataSourceProperties()
}

@Bean
@ConfigurationProperties(prefix = "spring.datasource.hikari")
fun dataSource(dataSourceProperties: DataSourceProperties): HikariDataSource {
    // HikariDataSource를 사용하기 위해 Hikari 설정 객체를 생성자로 넣은 HikariDataSource 객체 반환
    val dataSource: HikariDataSource =
        dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource::class.java).build()
    if (StringUtils.hasText(dataSourceProperties.name)) {
        dataSource.poolName = dataSourceProperties.name
    }
    return dataSource
}

 

기존엔 @ConfigurationProperties(prefix = "spring.datasource.hikari") 하나의 bean만 생성하여 HikariDataSource type의 클래스를 리턴하도록 하였는데 Spring Boot 버전이 올라가면서 설정하는 방식이 변경된 것 같다.

spring.datasource에 해당하는 빈을 만들고 spring.datasource.hikari 빈을 만들면서 만들어놓은 datasource를 hikariDataSource type으로 초기화하면서 dataSource를 반환하도록 했다.

 

오류 - Driver net.sf.log4jdbc.sql.jdbcapi.DriverSpy claims to not accept jdbcUrl, jdbc:log4jdbc:mariadb://istg15-db.fassto.ai:3306/fsswms?useUnicode=true&characterEncoding=utf8mb4&autoReconnect=true&allowMultiQueries=true

 

driverClass에 해당하는 JDBC가 없을 때 발생한다.

 

기존에는 mariadb를 사용할 때 mysql(runtimeOnly 'mysql:mysql-connector-java')을 JDBC로 사용해도 문제가 없었는데 Spring Boot 3으로 올리면서 엄격하게 타입 체크를 하는 것 같다.

 

mariadb(runtimeOnly("org.mariadb.jdbc:mariadb-java-client:3.3.2"))로 JDBC를 변경하니 오류 없이 DB 세팅은 완료되었다.

 

Spring Boot 3이 되면서 datasource 관련된 설정 방식이 기존과 다르게 많이 변경된 것 같다.

 

이번에 또 느낀게 인터넷에 있는 설정들은 내 작업물과 100% fit하지 않기 때문에 본인 설정 방식에 맞는 것을 오류 메시지를 통해서 파악해야한다!

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 에러' 카테고리의 다른 글

nvalidDataAccessApiUsageException: Executing an update/delete query 오류  (0) 2024.07.22
XML -> JAVA Class 매핑 시 발생한 에러  (0) 2024.05.09
오류: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/reactivestreams/Publisher  (0) 2023.03.09
오류: java.lang.ArithmeticException: Rounding needed with the rounding mode being set to RoundingMode.UNNECESSARY  (0) 2023.03.09
오류:org.springframework.dao.InvalidDataAccessApiUsageException: For input string: "XXX"; nested exception is java.lang.NumberFormatException: For input string: "XXX"  (0) 2023.03.08
Posted by UIJ

@Transactional 어노테이션에 대한 정리

IT 개발/개념 정리 2023. 11. 26. 13:27

@Transactional 어노테이션 사용 시 사용자가 지정한 rollback rules이 없을 경우 RuntimeException, Error일 때 롤백되고 checked Exception에선 롤백되지 않는다.

 

상황 : 같은 Class 내 오류가 발생해도 서로 다른 propagation을 설정해 부모 트랜잭션에서 오류가 발생해도 자식 트랜잭션은 커밋되게 동작시키려함

예상한 동작 방식 : saveContent내부의 save는 동작하지 않아도 updateContent내부의 save는 동작할 것으로 예상함.

이유 : require_new로 트랜잭션을 신규로 생성했고 부모에서 exception이 발생해도 자식은 트랜잭션이 신규로 생성되기 때문에 save될 것이라 예상함

    @Transactional(rollbackFor = Exception.class)
    public void saveContent(BoardDTO boardDTO) throws Exception {

        Board board = new Board(boardDTO);
        boardRepository.save(board);
        updateContent(1000L, boardDTO);
        throw new RuntimeException();

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void updateContent(Long contentId, BoardDTO boardDTO) {
        Board board = boardRepository.findById(contentId).orElseThrow();
        board.updateContent(boardDTO.getTitle(), boardDTO.getContent());
        boardRepository.save(board);
    }

 

위의 예제 코드로 테스트를 하였으나 내가 기대한 방식으로 동작하지 않았고 원인은 Spring에서 @Transactional 어노테이션에 대한 동작 방식 때문이었다. @Transaction 어노테이션은 Spring의 AOP를 통해 프록시 객체를 생성하여 사용된다.

 

Target 클래스가 인터페이스 구현체가 아니어서 테스트 코드상에서는 CGLib Proxy 방식으로 Target 클래스를 프록시 객체로 생성하여 코드에 끼워넣는 방식이 사용됐다.

 

문제는 Target 클래스를 프록시 객체로 생성의 특징으로 인해 발생했는데 동일한 Class내에 위치한 메서드에 각기 다른 @Transactional propagation 옵션을 설정했지만 메소드 단위가 아닌 Target클래스 단위로 설정되기 때문에 새로운 트랜잭션이 생성되지 않는다.

 

이를 해결하기 위해선 메소드를 다른 클래스로 분리(bean을 분리해줌)시키면 외부에서 호출하기 때문에 Target클래스 단위로 트랜잭션이 생성될 수 있고(propagation 전파 옵션에 따라) 부모가 실패해도 자식 트랜잭션은 커밋될 수 있도록 설정할 수 있다. 

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 개념 정리' 카테고리의 다른 글

kotlin에서 queryDSL 사용하기  (1) 2024.07.05
ByteArray -> human readable string  (0) 2024.04.29
Spring Security 환경에서 h2 console enabled : true일 때 오류  (0) 2023.09.10
[아이템 61] 박싱된 기본 타입보다는 기본 타입을 사용하라  (0) 2022.08.15
[아이템 54] null이 아닌, 빈 컬렉션이나 배열을 반환하라  (0) 2022.07.29
Posted by UIJ

Spring Security 환경에서 h2 console enabled : true일 때 오류

IT 개발/개념 정리 2023. 9. 10. 22:54

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'filterChain' defined in class path resource [com/example/securityspring/config/SecurityConfig.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).

This is because there is more than one mappable servlet in your servlet context: {org.h2.server.web.JakartaWebServlet=[/h2-console/*], org.springframework.web.servlet.DispatcherServlet=[/]}.

For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path.

 

위와 같은 오류 발생 문제의 원인은 h2 데이터베이스의 console 사용을 아래와 같이 허용해주었는데 h2 console 사용 시 서블릿 컨텍스트에 h2-console과 dispatcherServlet의 두 가지 서블릿이 매핑되어 어떤 서블릿을 사용해야하는지 알 수 없어 발생하는 오류

 

application.yml

spring:

  h2:
    console:
      enabled: true

 

filterChain의 requestMatchers에 MvcRequestMatcher, AntPathRequestMatcher 중 사용하려는 클래스를 명확하게 지정해줘야한다. 

 

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
	http.authorizeHttpRequests((authz) -> authz
    		.requestMatchers(new MvcRequestMatcher(introspector,"/api/hello")).permitAll()
		.anyRequest().authenticated())
		.httpBasic(Customizer.withDefaults());
	return http.build();
}

 

오류만 제대로 읽었어도 금방 찾을 수 있는 에러였다.

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 개념 정리' 카테고리의 다른 글

ByteArray -> human readable string  (0) 2024.04.29
@Transactional 어노테이션에 대한 정리  (0) 2023.11.26
[아이템 61] 박싱된 기본 타입보다는 기본 타입을 사용하라  (0) 2022.08.15
[아이템 54] null이 아닌, 빈 컬렉션이나 배열을 반환하라  (0) 2022.07.29
[아이템 51] 메서드 시그니처를 신중히 설계하라  (0) 2022.07.22
Posted by UIJ

오류: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/reactivestreams/Publisher

IT 개발/에러 2023. 3. 9. 22:10
    • 오류 메시지
      • org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/reactivestreams/Publisher
    • 원인
      • spring-boot-starter-webflux dependency 누락
    • 해결
      • spring-boot-starter-webflux dependency 추가

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'IT 개발 > 에러' 카테고리의 다른 글

XML -> JAVA Class 매핑 시 발생한 에러  (0) 2024.05.09
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine suitable jdbc url - spring boot 3 datasource 설정  (1) 2024.04.28
오류: java.lang.ArithmeticException: Rounding needed with the rounding mode being set to RoundingMode.UNNECESSARY  (0) 2023.03.09
오류:org.springframework.dao.InvalidDataAccessApiUsageException: For input string: "XXX"; nested exception is java.lang.NumberFormatException: For input string: "XXX"  (0) 2023.03.08
오류: Resolved [org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet]  (0) 2023.03.07
Posted by 큐그
이전페이지 다음페이지
블로그 이미지

IT 관련 및 신변잡기에 대한 포스팅을 해보고자 하는 블로그입니다.

by 큐그

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • CGLIB Proxy
  • bytearrays -> string
  • 네트워크
  • 리뷰
  • bytearrays
  • require_new
  • 오마카세
  • ClassCastException
  • 제네릭
  • MvcRequestMatcher
  • 인터페이스
  • ArithmeticException
  • 매개변수
  • 에러
  • 상속
  • 클래스와 인터페이스
  • 맛집리뷰
  • effective java
  • 맛집
  • 데이터베이스
  • Spring Batch
  • group_concat querydsl
  • IntelliJ
  • java
  • 이펙티브 자바 3/E
  • 오류
  • Effective JAVA 3/E
  • 이펙티브 자바
  • 자바
  • Target클래스

글 보관함

«   2025/06   »
일 월 화 수 목 금 토
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

링크

카테고리

분류 전체보기 (65)
IT 개발 (58)
개념 정리 (30)
명령어 (2)
에러 (17)
코딩테스트 (2)
초대장 (1)
구매 (2)
맛집 (3)
식당 (2)
카페 (1)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
큐그's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

신변잡기 분석 및 설계

IT 관련 및 신변잡기에 대한 포스팅을 해보고자 하는 블로그입니다.

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • 분류 전체보기 (65)
    • IT 개발 (58)
      • 개념 정리 (30)
      • 명령어 (2)
      • 에러 (17)
      • 코딩테스트 (2)
    • 초대장 (1)
    • 구매 (2)
    • 맛집 (3)
      • 식당 (2)
      • 카페 (1)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바