我正在尝试创建 DatastoreRepository 类的 bean,但我使用
spring-boot 2.1.3
时收到以下错误
Description:
The bean 'bookRepository', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
这是我的项目结构,我在根包中有应用程序主运行类,如下所示
com.mycompany.project
--Application.java
--controller
--domain
--repository
带有
@SpringBootApplication
的类位于根包中
这是我的存储库类
import org.springframework.cloud.gcp.data.datastore.repository.DatastoreRepository;
public interface BookRepository extends DatastoreRepository<Book, Long>{
}
这是我的领域类
import org.springframework.cloud.gcp.data.datastore.core.mapping.Entity;
import org.springframework.data.annotation.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity(name = "books")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
@Id
Long id;
String title;
}
这是我的控制器类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AppUserController {
@Autowired
BookRepository bookRepository;
@GetMapping("/booksave")
public String helloworld() {
bookRepository.save(new Book(3L, "author"));
return "book saved";
}
}
这是我的应用程序类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我认为问题在于您使用注释的方式,尝试将注入更改为构造函数,例如:
@RestController
public class AppUserController {
private BookRepository bookRepository;
@Autowired
public AppUserController (
BookRepository bookRepository){
this.bookRepository= bookRepository;
}
@GetMapping("/booksave")
public String helloworld() {
bookRepository.save(new Book(3L, "author"));
return "book saved";
}
}
将此注释 @EnableDatastoreRepositories 添加到您的 Application.java
使用Spring数据休息怎么样:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
您无需编写控制器代码
import org.springframework.cloud.gcp.data.datastore.repository.DatastoreRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "xxxxxs", path = "xxxx")
public interface XXXXXRepository extends DatastoreRepository<XXXXX, String>
招摇配置!!!
@Configuration
@EnableSwagger2WebMvc
@Import(SpringDataRestConfiguration.class)
public class SwaggerConfig {