zoukankan      html  css  js  c++  java
  • springboot使用jpa+mongodb时,xxxRepository不能Autowired的问题

    springboot启动类:

    @SpringBootApplication
    public class MainApp {
    
        public static void main(String[] args) {
    
            SpringApplication.run(MainApp.class, args);
        }
    }

    jpa数据库操作类:

    public interface UserDao extends MongoRepository<User, String> {
    }

    单元测试类:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(MainApp.class)
    public class UserDaoTest {
        @Autowired
        private UserDao userDao;
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @Test
        public void add() throws JsonProcessingException {
            for(int i = 1; i <= 5; i++) {
                User user = new User();
                user.setName("测试" + i);
                user.setSex((i%2 == 0) ? 0 : 1);
                user.setPhone("1511111000" + i);
                user.setCreateTime(new Date());
                User save = userDao.save(user);
                System.out.println("保存结果:" + objectMapper.writeValueAsString(save));
            }
        }
    }

    执行结果:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserDaoTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mlxs.springboot04.mongodb.dao.UserDao UserDaoTest.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mlxs.springboot04.mongodb.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    解决方法:

    在springboot启动类中添加@EnableMongoRepositories注解,标注mongoRepository类的路径

    @SpringBootApplication
    @EnableMongoRepositories(basePackages = {"com.mlxs.springboot04.mongodb.dao"})
    public class MainApp {
    
        public static void main(String[] args) {
    
            SpringApplication.run(MainApp.class, args);
        }
    }
  • 相关阅读:
    NodeJS旅程 : module 不可忽略的重点
    NodeJS旅程 : Less
    NodeJS旅程 : express
    新的旅程:NodeJS
    活用命令模式
    20145226《信息安全系统设计基础》第0周学习总结
    20145226夏艺华 《Java程序设计》第1周学习总结
    学习 MySQL-DBA常用SQL汇总
    关于旗舰店直通车的由来
    学习 Mysql
  • 原文地址:https://www.cnblogs.com/yangzhenlong/p/6400416.html
Copyright © 2011-2022 走看看