我正在尝试用Spring创建REST API Service。我有以下结构和类
app\
├── controller\
│ └── OrderController.java\
├── dto\
│ └── OrderDto.java\
├── model\
│ └── Order.java\
├── repository\
│ └── OrderRepository.java\
├── service\
│ ├── IOrderService.java\
│ └── OrderService.java\
└── Application.java
Order.java
@Entity @Table(name = "order")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Order {
//getters, setters, constructors
OrderController.java
@RestController
public class OrderController {
@Autowired
private IOrderService orderService;
//some code
IOrderService.java
public interface IOrderService {
List<Order> findAll();
}
OrderService.java
@Service
public class OrderService implements IOrderService {
@Autowired
private OrderRepository orderRepository;
@Override
public List<Order> findAll() {
return (List<Order>) orderRepository.findAll();
}
OrderRepository.java
@Repository
public interface OrderRepository extends JpaRepository<Order, UUID> {
}
Application.java
@SpringBootApplication
@EnableJpaReposotories(basePackages = "app.repository")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
AppConfig.java
@Configuration
public class AppConfig {
@Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
return sessionFactory;
}
}
application.properties
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:8080/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.projectlombok:lombok:1.18.26'
implementation 'org.springframework.data:spring-data-commons:3.0.3'
implementation 'org.springframework.data:spring-data-jpa:3.0.3'
implementation 'jakarta.persistence:jakarta.persistence-api:3.1.0'
implementation 'org.springframework:spring-context:6.0.6'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
似乎仓库对服务不可见。我尝试在Application类中添加一些注解(例如@EnableJpaRepositories(base_packages = {“app.repository”})),但出现类似的错误。我该怎么办?UPD -现在消息为Field orderRepository in app.service.OrderService required a bean named 'entityManagerFactory' that could not be found
2条答案
按热度按时间irlmq6kh1#
1.您的依赖项过于冗长,请使用
spring-boot-sarter-data-jpa
而不是单个依赖项。1.删除
AppConfig
,因为这会(部分)破坏Sping Boot 自动配置,或者至少是LocalSessionFactoryBean
。@Repository
除了噪声和混乱之外没有添加任何东西1.假设您的
@SpringBootApplication
注解类位于顶级包中,则不需要@EnableJpaRepositories
。PRO-TIP:使用构造函数代替字段进行依赖注入。
当然,你也可以为你的控制器做同样的事情。
rkkpypqq2#
缺少@Repository注解。