2

하루를 검색하고 모든 설정 (앱 컨텍스트)과 주석 (autowire, inject, component 등)을 시도한 후에 pojo 클래스가 작동하도록 삽입 할 수없는 것 같습니다. 저장소가 성공적으로 - 값은 항상 null입니다. 컨트롤러가 아닌 컨트롤러에 주입하는 것이 스프링 데이터 나머지 아키텍처에 위배되는지 궁금해지기 시작했습니다.스프링 데이터 레스트 저장소를 유틸리티 클래스에 넣기

package com.test.springservice; 

import ... 

@Configuration 
@ComponentScan 
@EnableJpaRepositories 
@Import(RepositoryRestMvcConfiguration.class) 
@ImportResource("classpath:WEB-INF/applicationContext.xml") 
@EnableAutoConfiguration 
@PropertySource("application.properties") 
public class Application { 
    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 

내 작업 저장소 및 모델 : :

package com.test.springservice.greek; 

import ... 

@RepositoryRestResource 
public interface GreekLetterRepository extends CrudRepository<GreekLetter, Integer> { 
    @Query("SELECT l FROM GreekLetter l WHERE l.translit Like :translit% ORDER BY length(l.translit) Desc") 
    public List<GreekLetter> findByTranslitStartsWith(@Param("translit") String translit); 

} 

package com.test.springservice.greek.model; 

import .... 

@Entity 
@Table(name="letters", catalog="greek") 
public class GreekLetter extends Letter { 
    public GreekLetter() {} 
    public GreekLetter(String name, String translit, String present, String types) { super(name,translit,present,types); } 
} 
이 상황을 그립니다

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/data/jpa 
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> 

    <jpa:repositories base-package="com.test.springservice"/> 

</beans> 

내 주요 클래스 : 여기

은 (스프링 문서에서 가져온) 내 응용 프로그램 컨텍스트입니다

마지막으로 저장소를 삽입 할 수없는 클래스입니다 :

package com.test.springservice.greek.model; 

import ... 

public class GreekString extends Letters { 

    @Autowired 
    public GreekLetterRepository repository; // this is null (class not managed by container) 

    public GreekString(String str) { 
     super(); 
     setTranslit(str); 
     if (this.getTranslit().equals(this.getPresent())) { setPresent(str); } 
    } 
    public void setTranslit(String str) { // litterates from str as translit 
     List<Letter> lets = new ArrayList<Letter>(); 
     for (int i = 0; i < str.length(); i++) { 
      String partialWord = str.substring(i); 
      String partialWord0 = partialWord.substring(0,1); 
      List<GreekLetter> potentialMatches = repository.findByTranslitStartsWith(partialWord0); 
      .... 
     } 
     ....   
    } 
    .... 
} 

누구나 접근법에 기본적인 결함이 있습니까?

미리 감사드립니다.

답변

2

repository 스프링이 @Autowired 주석을 통해 주입 할 수 있기 전에 문제가 발생했습니다.

public GreekString(String str, GreekLetterRepository greekLetterRepository)

난 당신이 빈을 인스턴스화하는 경우 표시되지 않습니다하지만 자바 구성에있는 경우, 당신이이 작업을 수행 할 수 있습니다

한 수정 GreekLetterRepository의 생성자를 기반으로 배선을 사용할 수 way :

@Bean 
public GreekString something(GreekLetterRepository greekLetterRepository) { 
    return GreekString("something", greekLetterRepository); 
} 

이제는 제대로 작동해야합니다.

그러나 생성자 내에서 즉시 저장소를 사용하지 않는 것이 좋습니다. 종속 Bean을 사용하는 더 좋은 장소는 전체 bean이 완전히 초기화 된 후에입니다. @PostConstruct과 함께 메소드에 주석을 달아 Bean이 완전히 호출되면 호출 할 수 있습니다. 초기화,이 방법 :

public class GreekString extends Letters { 

    @Autowired 
    public GreekLetterRepository repository; 

    public GreekString(String str) { 
     super(); 

    } 
    ..... 

    @PostConstruct 
    public void init() { 
     setTranslit(str); 
     ... 
    } 
} 

하나 더 참고 :

@EnableJpaRepositories("com.test.springservice:) 및 XML jpa:repositories는 같은 목적으로, 당신은 가서 XML 구성을 제거 할 수있는 역할을

+0

그는 Spring Boot를 사용함에 따라 완전히 제거 할 수 있으며, @ PropertySource와 @Import (RepositoryRestMvcConfiguration.class)에도 동일하게 적용됩니다. '@ Configuration','@ ComponentScan' 및'@ EnableAutoConfiguration'을'@ SpringBootApplication'으로 대체 할 수있는 것만 남았습니다 (Spring Boot 1.2.0이 사용 된 버전 인 경우). –

+0

변경 사항을 적용한 후에도 주입 된 저장소에서 null이 계속 발생하기 때문에 대답을 수락하지 않았습니다. –

+0

github repo에서 코드를 공유 할 수 있다면 해결할 수 있습니다. 문제가 어디에서 발췌 될지 알기가 어렵습니다. –

관련 문제