java - 如何创建存储库类的 bean

标签 java spring spring-mvc javabeans

我正在使用 spring mvc 测试框架进行单元测试。

以下是我的源代码: com.exmple.main

MyController.java

@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> myControllerFunction(@RequestBody final Object jsonRequest) {
        /* do something */

        return response;
    }
}

MyRepository.java

@Repository
public interface MyRepository extends JpaRepository<My, String> {

    @Query(value="select * from my d where (d.start_date<to_date(:date,'YYYY/DD/MM')) and (d.end_date>to_date(:date,'YYYY/DD/MM'))", nativeQuery=true)
    List<My> findByDate(@Param("date") String date);
}

MyService.java

public interface MyService {
    List<My> findByDate(String date);
}

MyServiceImpl.java

@Service

public class MyServiceImpl implements MyService {
    @Autowired
    MyRepository destRepo;

    @Override
    public List<My> findByDate(String date) {
        List<My> listDest = destRepo.findByDate(date);

        return listDest;
    }
}

com.example.test

MyControllerTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfig.class})
@WebAppConfiguration
public class MyControllerTest {
    private MockMvc mockMvc;

    @Autowired
    MyService myService;

    @Autowired
    protected WebApplicationContext webApplicationContext;

    @Before
    public void setup() throws Exception {
        // this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void listAllMy() throws Exception {

    }
}

TestConfig.java

@Configuration
public class TestConfig {
    @Bean
    public MyService myService() {
        // set properties, etc.
        return new MyServiceImpl();
    }
}

当我运行测试时,显示以下错误 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException

我知道发生异常是因为 MyService 没有找到 MyRepository 的任何 bean。 但我不知道如何创建存储库 bean。 请教我如何使用 Java(不是 xml)创建存储库类的 bean。

最佳答案

您需要在配置类中启用 JPA 存储库,指定包含存储库的包,如下所示

@Configuration
@EnableJpaRepositories(basePackages = {
    "com.example.repository"
})
public class TestConfig {
    @Bean
    public MyService myService() {
        // set properties, etc.
        return new DestinationServiceImpl();
    }
}

编辑:看起来您还没有定义 entityManager 和 dataSource。引用a tutorial here并回答类似问题 here

关于java - 如何创建存储库类的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987743/

相关文章:

java - mockito:类 [X] 未准备好进行测试

java - Spring MVC Controller 代码 : getOutputStream() has already been called for this response

java - WSO2 ESB 定制连接器

java - 打开新部分时如何打开并自动关闭警报对话框?

java - 使用多个事务管理器时没有 Hibernate session 绑定(bind)到线程

java - Spring 目录监听器

java - Spring:在属性文件中定义 @RequestMapping 值

java - Apache Camel : Need advice for Routing

java - 使用 Apache POI 在 Excel 单元格中写入数字

java - Spring RequestBody需要加载嵌套的Object