Spring MVC @pathvariable annotated不会将值从接口传递给实现

时间:2014-04-25 10:43:27

标签: spring spring-mvc annotations

服务类

@Service

@RequestMapping(value = "employees")

public interface EmployeeService {

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public @ResponseBody Employee getEmployee(@PathVariable("id") int employeeId) throws EmpException;

    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody List<Employee> getAllEmployees() throws EmpException;

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody Employee createEmployee(@RequestBody Employee employee) throws EmpException;


    @RequestMapping(value ="{id}", method = RequestMethod.DELETE)
    public @ResponseBody UserInfo deleteEmployee(@PathVariable("id") int employeeId) throws EmpException;

    @RequestMapping(value="{id}", method = RequestMethod.PUT)
    public @ResponseBody Employee updateEmployee(@RequestBody Employee employee,@PathVariable("id") int employeeId) throws EmpException;

}

实施班

@Service("employeeService")

public class EmployeeServiceImpl implements EmployeeService {    
   @Autowired
   private Employee employee;

   private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class);
public Employee getEmployee(@PathVariable("id") int employeeId) throws EmpException {
        logger.info("Start getEmployee. ID="+employeeId);
        employee = employeeDao.getEmployee(employeeId);
        if(employee != null) {
            return employee;
        } else {
            throw new EmpException("ID: "+employeeId+" is not available");
        }
    }
}

在实现类中我也使用了@pathvariable注释,然后只有employeeId的值将从接口传递给实现,否则将发生空指针表达式。在不使用@path变量的情况下将值从接口传递给实现的其他方法。

1 个答案:

答案 0 :(得分:2)

请求映射不在服务类上,而是在控制器上。

您需要@Controller annotation