2016-12-23 1 views
6

현재 Java Spring Boot Application을 Kotlin으로 다시 작성하려고합니다. @Service으로 주석이 달린 모든 클래스에서 종속성 삽입이 올바르게 작동하지 않는 문제가 발생했습니다 (모든 인스턴스는 null). 다음은 예입니다 자바에서 같은 일을스프링 부트 @ @Service의 Kotlin과 함께 사용하면 항상 null입니다.

@Service 
@Transactional 
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) { 
    //dsl and teamService are null in all methods 
} 

하는 것은 아무 문제없이 작동합니다

@Service 
@Transactional 
public class UserServiceController 
{ 
    private DSLContext dsl; 
    private TeamService teamService; 

    @Autowired 
    public UserServiceController(DSLContext dsl, 
          TeamService teamService) 
    { 
     this.dsl = dsl; 
     this.teamService = teamService; 
    } 

내가 코 틀린 모든 것을에서 @Component와 구성 요소에 주석을하면 잘 작동 :

@Component 
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) { 
    //dsl and teamService are injected properly 
} 

구글 Kotlin과 @Autowired에 대한 여러 가지 접근 방식을 제공했지만 모두 동일한 결과를 가져 왔습니다. NullPointerException Kotlin과 Java의 차이점을 알고 싶습니다. 어떻게 해결할 수 있습니까?

+0

val을 var로 변경해 보셨습니까? –

+0

[스프링 프록시 클래스 및 Kotlin의 [null 포인터 예외]의 가능한 복제본 (http://stackoverflow.com/questions/37431817/null-pointer-exception-in-spring-proxy-class-and-kotlin) – miensol

+0

예 둘 다 시도했다. – Deutro

답변

4

어떤 스프링 부트 버전을 사용하십니까? 1.4 Spring Boot는 Spring Framework 4.3을 기반으로하므로 이후 @Autowired 주석을 사용하지 않고 생성자 삽입을 사용할 수 있어야합니다. 너 그거 해봤 니?

그것은 다음과 같이 나를 위해 작동합니다 :

@Service 
class UserServiceController(val dsl: DSLContext, val teamService: TeamService) { 

    // your class members 

} 
+1

개를 넣으세요 :) – davidxxx

+0

안녕하세요, '기본 생성자가 없습니다'를 얻지 않고 속성을 만들지 않고이 작업을 수행 할 수있는 방법이 있습니까? null -할 수 있는? *** (참고 일부 매개 변수는 저장소입니다) *** – jasperagrante

+0

나는 이미 내 문제를 해결했습니다. '기본 생성자 없음'또는 @Autowired가 이미있는 사용자의 경우 생성자에 기본값이 없는지 확인하십시오. – jasperagrante

2

난 그냥 정확히 같은 문제에 부딪쳤다 - 분사가 잘 작동하지만, @Transactional 주석을 추가 한 후 모든 autowire가 필드가 null입니다.

내 코드 :

@Service 
@Transactional 
open class MyDAO(val jdbcTemplate: JdbcTemplate) { 

    fun update(sql: String): Int { 
     return jdbcTemplate.update(sql) 
    } 

} 
여기서 문제는 봄이 클래스에 대한 프록시를 만들 수 없습니다 그래서 방법은, 코 틀린에 기본적으로 최종 점이다

:

o.s.aop.framework.CglibAopProxy: Unable to proxy method [public final int org.mycompany.MyDAO.update(... 

"열기"를

고정 코드 :

@Service 
@Transactional 
open class MyDAO(val jdbcTemplate: JdbcTemplate) { 

    open fun update(sql: String): Int { 
     return jdbcTemplate.update(sql) 
    } 

} 
방법은 문제를 해결
+0

Kotlin에는 이러한 클래스를 열 수있는 빌드 플러그인이 있습니다. https://kotlinlang.org/docs/reference/compiler-plugins.html –

관련 문제