(8)controller,service程序填空,改错
时间: 2024-05-13 10:14:37 浏览: 53
1. 填空:
Controller:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("/")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
}
```
Service:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
@Override
public User createUser(User user) {
return userRepository.save(user);
}
}
```
2. 改错:
Controller:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("/")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
}
```
Service:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
@Override
public User createUser(User user) {
return userRepository.save(user);
}
}
```
以上代码没有错误。
阅读全文