【发布时间】:2016-05-24 05:17:54
【问题描述】:
我使用 spring boot 和 spring mvc 创建了一个新服务。
UserEntity.class:
@Entity
@Table(name = "users")
public class UserEntity {
private long id;
private String username;
private String password;
private boolean active;
private boolean login;
public UserEntity(UserDto dto) {
this.id = dto.getId();
this.username = dto.getUsername();
this.password = dto.getPassword();
this.active = dto.isActive();
}
// getters&setters...
}
UserDto.class:
public class UserDto {
private long id;
private String username;
private String password;
private boolean active;
public UserDto(long id, String username, String password, boolean active) {
this.id = id;
this.username = username;
this.password = password;
this.active = active;
}
// getters&setters...
}
用户存储库:
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}
UserServiceImpl.class:(和 UserService 接口)
@Service
@Transactional
public class UserServiceImpl implements UserService {
private final UserRepository repo;
@Autowired
public UserServiceImpl(UserRepository repo) {
this.repo = repo;
}
@Override
public boolean saveUser(UserDto dto) {
UserEntity user = new UserEntity(dto);
repo.save(user);
return true;
}
}
用户控制器类:
@RestController
public class UserController {
private final UserService service;
@Autowired
public UserController(UserService service) {
this.service = service;
}
@RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(@RequestBody UserDto userDto) {
service.saveUser(userDto);
}
}
Application.class:
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
我的 Spring Boot 项目正确启动。但是当我使用 IntelliJ Test Restful Web Service Tool 测试我的服务时,我遇到了一个错误:
回复:
{"timestamp":1464066878392,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/users"}
有什么问题?
【问题讨论】:
-
我认为存储库应该是
@Autowired,而不是构造函数。当 repo 已经自动装配时,为什么你甚至需要 UserServiceImpl 的构造函数? -
而不仅仅是
@EnableAutoConfiguration使用@SpringBootApplication。没有它,就不会扫描组件,也不会检测到您的 bean。
标签: java spring-mvc intellij-idea