Spring boot Spring启动集成测试,@Autowired工作,@Inject不工作,为什么?
我在一个Spring引导应用程序上工作,我已经编写了一个服务,我想在集成测试中测试这个服务。因此,我想将服务注入到我的测试中。如果使用@Inject注释,则服务为空。如果我使用@Autowired,服务将被注入,测试将正常工作。我认为注释应该做得差不多,唯一的区别是@Autowired在没有可用bean的情况下会失败,因为它默认设置为required=true。服务有一个接口,我根据字段名选择实现 接口:Spring boot Spring启动集成测试,@Autowired工作,@Inject不工作,为什么?,spring-boot,dependency-injection,annotations,autowired,inject,Spring Boot,Dependency Injection,Annotations,Autowired,Inject,我在一个Spring引导应用程序上工作,我已经编写了一个服务,我想在集成测试中测试这个服务。因此,我想将服务注入到我的测试中。如果使用@Inject注释,则服务为空。如果我使用@Autowired,服务将被注入,测试将正常工作。我认为注释应该做得差不多,唯一的区别是@Autowired在没有可用bean的情况下会失败,因为它默认设置为required=true。服务有一个接口,我根据字段名选择实现 接口: import org.springframework.core.io.ByteArrayR
import org.springframework.core.io.ByteArrayResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
public interface FileService {
boolean storeDicomZip(InputStream stream, long caseId);
.
.
.
}
实施:
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import java.io.*;
import java.nio.file.Files;
import java.util.Optional;
@Service
public class FileSystemFileService implements FileService {
.
.
.
}
以及测试:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
public class FileSystemFileServiceTest {
@Autowired
private FileService fileSystemFileService;
@Test
public void storeDicomZip() throws Exception {
InputStream stream = new ByteArrayInputStream("TEST".getBytes());
fileSystemFileService.storeDicomZip(stream, 3);
Assert.assertTrue(fileSystemFileService.getDicomZipVersions(3) == 1);
}
.
.
.
}
如前所述,如果我使用@Autowired,就像这里一样,它可以工作;如果我使用@Inject,它不会工作,因为fileSystemFileService为null
有人知道为什么会这样吗?我必须改变什么才能使用@Inject 到目前为止还没有答案?