gpt4 book ai didi

java - @Autowired 存储库为空

转载 作者:太空宇宙 更新时间:2023-11-04 10:56:51 32 4
gpt4 key购买 nike

ExampleRepository注入(inject)者@Autowired测试类中的注释效果很好,但注入(inject)服务类中的注释为空。为什么会发生这种情况以及如何解决它?

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());
}

// ...
}

最佳答案

@Repository注释添加到接口(interface)ExampleRepository

关于java - @Autowired 存储库为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47284006/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com