@Autowired Repository null

时间:2017-11-14 11:00:08

标签: java spring spring-boot spring-data-jpa

ExampleRepository注释注入到测试类中的

@Autowired运行良好,但是注入服务类是空的。为什么会发生这种情况?如何解决?

Repository class

public interface ExampleRepository extends JpaRepository<Example, Long> {

    // ...
}

Service class

@Service
public class Feed {

    @Autowired
    private ExampleRepository exampleRepository;

    private File file;

    public Feed(String file) {
        this.file = new File(file);
    }

    // ...
}

Test class

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Rollback(false)
public abstract class ExampleTests {

    @Autowired
    private ExampleRepository exampleRepository;

    @BeforeEach
    public void setUp() {
        restoreInitialData();
    }

    protected void restoreInitialData() {
        this.exampleRepository.deleteAll();
    }

    @Test
    public void test() {
        Feed feed = new Feed("example.json");
        Optional<Example> example = feed.ingest();
        assertTrue(example.isPresent());
    }

    // ...
}

1 个答案:

答案 0 :(得分:0)

@Repository注释添加到界面ExampleRepository