这是userService类,它需要找不到类型为com.example.repository.userRepository
的bean
package com.example.services;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.modal.User;
import com.example.repository.userRepository;
@Service
@Transactional
public class UserService {
@Autowired
private userRepository userRepository;
public UserService() {
super();
}
public UserService(userRepository userRepository)
{
this.userRepository = userRepository;
}
public void saveMyuser(User user) {
userRepository.save(user);
}
}
错误消息显示为:
考虑在您的配置中定义类型为
'com.example.repository.userRepository'
的bean。
这是存储库:
package com.example.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.modal.User;
public interface userRepository extends CrudRepository<User,Integer> {
}
这是应用程序类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
public class TutorialProjectApplication {
public static void main(String[] args) {
SpringApplication.run(TutorialProjectApplication.class, args);
}
}
答案 0 :(得分:5)
似乎userRepository
接口不在spring-boot默认扫描范围内,即该存储库接口的软件包不相同,或者是带有@SpringBootApplication
注释的类的子软件包。如果是这样,则需要在主类上添加@EnableJpaRepositories("com.example.repository")
。
更新:
查看更新后的帖子后,您需要向@EnableJpaRepositories("com.example.repository")
类添加TutorialProjectApplication
答案 1 :(得分:3)
始终保留@SpringBootApplication
主类的外部程序包,以便它将自动扫描所有子程序包。
在您的情况下,包com.example.demo;
中有主类,而package com.example.repository;
中的存储库是不同的包。因此spring boot无法找到存储库。
因此,您必须使Spring Boot知道存储库的位置。
所以现在您有2个解决方案。
1。将存储库类放在Main class包的子包中。
2。或者在主类中使用@EnableJpaRepositories("com.example.repository")
。
答案 2 :(得分:2)
在您的存储库中,您需要注释该类
@Repository
public interface userRepository extends CrudRepository<User,Integer> {
}