Spring JPA bean找不到异常

时间:2018-04-30 15:58:11

标签: java spring-boot spring-data-jpa

我在我的项目中使用spring JPA。我的存储库bean没有被调用。我得到一个null pointerException。

我的存储库是:

public interface UserRepository extends JpaRepository<User, Long>{

}

我的实体网址:

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;

    @Column(name = "emailid")
    String emailId;

    @Column(name="role")
    UserRole role;


}

我的JPA配置:

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "appentitymanagerfactory",
transactionManagerRef = "apptransactionmanager",
basePackages = "com.tree.employeeapp.entity")
public class JpaConfiguration {
    @Bean
    (name = "appentitymanagerfactory")
    public LocalContainerEntityManagerFactoryBean externalEntityManagerFactory(
         EntityManagerFactoryBuilder   builder, @Qualifier("employeeappdatasource") DataSource dataSource) {
        return builder.dataSource(dataSource)
                .packages("com.tree.employeeapp.entity")
                .build();
    }

    @Bean(name = "apptransactionmanager")
      public PlatformTransactionManager barTransactionManager(
        @Qualifier("appentitymanagerfactory") EntityManagerFactory
        entityManagerFactory
      ) {
        return new JpaTransactionManager(entityManagerFactory);
      }
}

我的控制器是:

@Controller
public class treeAppsControllerImpl implements treeAppsController{

private UserRepository userRepository;
@Autowired
public treeAppsControllerImpl(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
public String getAllUsers(Model model) {
    List<Users> listOfUsers = new ArrayList<>();

    for(User user: userRepository.findAll())
            listOfUser.add(user);

    List<User> listOfUser = UserRepository.findAll();
    model.addAllAttributes(listOfUsers);
    return "getAllUsers";
}

日志显示此错误:

com.tree.employeeapp.controller.treeAppsControllerImpl中构造函数的参数0需要一个无法找到的类型为“com.tree.employeeapp.repository.UserRepository”的bean。 行动: 考虑在配置中定义类型为“com.tree.employeeapp.repository.UserRepository”的bean。

1 个答案:

答案 0 :(得分:0)

将UserRepository标记为存储库

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
}