[英]DomainClassConverter not working in Spring Boot
我有一個非常簡單的 Spring Boot MVC 項目,我在其中嘗試使用 DomainClassConverter 直接加載實體。 但似乎找不到 DomainClassConverter。 訪問“localhost:8080/one/2”url 時出現以下錯誤:
無法將類型“java.lang.String”的值轉換為所需類型“com.example.test.data.Customer”:找不到匹配的編輯器或轉換策略
但是 DomainClassConverter 應該由 Spring 啟動並管理轉換。
我還嘗試通過 @EnableSpringDataWebSupport 注釋明確啟用它,但它也沒有工作。
這是我的 controller 代碼:
@Controller
public class TestController {
@Autowired
private CustomerRepository customerRepository;
@GetMapping("/all")
public void all(Model model) {
Iterable<Customer> customers=customerRepository.findAll();
model.addAttribute("customers",customers);
};
@GetMapping("/one/{customer_id}")
public void one(@PathVariable("customer_id") Customer customer, Model model) {
model.addAttribute("customer",customer);
};
}
客戶代碼:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
private Long id;
@Getter
@Setter
private String firstName;
@Getter
@Setter
private String lastName;
protected Customer() {
}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
CustomerREpositoy:
public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
Customer findById(long id);
}
應用程序:
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class);
}
}
最后是 build.graddle:
plugins {
id 'org.springframework.boot' version '2.3.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
// testImplementation 'org.springframework.security:spring-security-test'
}
test {
useJUnitPlatform()
}
任何想法?
您嘗試將customer_id
(路徑變量)作為客戶 object。 因此,當您嘗試訪問localhost:8080/one/2
時會出現上述錯誤。
將customer_id
(路徑變量)數據類型更改為相關數據類型(字符串、整數等),如下所示,
@GetMapping("/one/{customer_id}")
public void one(@PathVariable("customer_id") String customerId, Model model) {
----
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.