This question already has answers here:
Why is my Spring @Autowired field null?
                                
                                    (16个答案)
                                
                        
                                3年前关闭。
            
                    
我有以下实体类,在创建对象之前,应调用getUniqueSlug方法来检查是否已经存在具有相同名称的项目。

@Entity public class Category {
@Column private Long id;

@Column(nullable = false) private String name;

@Column(nullable = false) private String slug;

@Autowired private CategoryRepository categoryRepository;

public String getUniqueSlug(String name) {
    int i = 1;

    while (this.categoryRepository.findBySlug(Slug.toSlug(name)) != null) {
        name = name + " " + i;
        i++;
    }

    return Slug.toSlug(name);
}

// Constructors

public Category() {
}

public Category(String name) {
    this.name = name;
    this.slug = getUniqueSlug(name);
}

// Getters and setters


我也有以下测试来检查它是否正确执行:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration public class CategoryTest {

private MockMvc mockMvc;

@Autowired private CategoryRepository categoryRepository;

@Autowired ObjectMapper objectMapper;

@Autowired private WebApplicationContext webApplicationContext;

@Before public void setUp() throws Exception {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    this.categoryRepository.deleteAll();
    this.categoryRepository.save(new Category("My category name"));
}

@Test public void testUniqueSlug() throws Exception {
    String slug = "My category name";
    int integer = 1;
    while (categoryRepository.findBySlug(Slug.toSlug(slug)) != null) {
        slug = slug + " " + integer;
        integer++;
    }
    this.categoryRepository.save(new Category(slug));
    System.out.println(this.categoryRepository.findAll());
}


运行该测试时,得到了NullPointerException,因此我认为问题出在自动装配Category类中的存储库中。到底在哪里?

最佳答案

您应该根据MVC概念将所有方法与实体类分开。
所有方法都通过自动装配的存储库定位到Service类中。
还要检查应用程序上下文是否包含您的存储库bean。

10-07 16:18