我用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...
}
UserRepository:
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}
UserServiceImpl.class :(和UserService Interface)
@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;
}
}
UserController.class:
@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"}
有什么问题?
答案 0 :(得分:0)
我的建议是从UserController和UserServiceImpl类中删除构造函数,不需要它们。然后,将@Autowired
注释分配给声明。另外,我认为你不需要制作它们final
。
UserServiceImpl.class:
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository repo;
@Override
public boolean saveUser(UserDto dto) {
UserEntity user = new UserEntity(dto);
repo.save(user);
return true;
}
}
UserController.class:
@RestController
public class UserController {
@Autowired
private UserService service;
public UserController(UserService service) {
this.service = service;
}
@RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(@RequestBody UserDto userDto) {
service.saveUser(userDto);
}
}