Spring Web 开发实践

Spring 3.0 版本。

@Path("/student") // 父 Path
@Produce({"application/json"})
public class StudentEndPoint {
  
  // Spring 2.5 开始提供了 @Autowired 自动装配,替换了基于 set 方法的依赖注入模式
  @Autowired StudentService service;

  @Get // HTTP 动词对应的 Restful
  @Produces({"application/json"})
  @Path("/info")
  public void getInfo(@QueryParam("id") String id) {
    ...
  }
  
  @Post // HTTP 动词对应的 Restful
  @Comsumes(MediaType.APPLICATION.JSON)
  @Path("/info")
  public void updateInfo(String payload) {
    ...
  }
}

@Component 注解

作用:把普通的 POJO 实例化为 Spring 容器中的 Bean。
例如:

@Component
public class StudentService {
  ...
}

通过 @Component 注解,则 无需 添加如下的 Bean 配置:

<bean id="studentService" class="StudentService">
  ...
</bean>

自动装配

Spring 2.5 开始提供了基于注解的自动装配机制来简化依赖注入。

  • ** @Autowired**:基于 类型 的自动装配注入
  • ** @Resource**:基于 名称 的自动装配注入

例如:

public class StudentService {
  @Resource(name="studentDAO")
  StudentDAO studentDAO;
}

以上的 @Resource 代码替换了如下的操作:

// set 方法
public void setStudentDAO(StudentDAO studentDAO) {
  this.studentDAO = studentDAO;
}
<!-- 配置 StudentService 的实例 studentService -->
<bean name="studentService" class="StudentService">
  <!-- 注入 studentDAO 这个 bean -->
  <property name="studentDAO" ref="studentDAO" />
  ...
</bean>

关于 PUT 和 DELETE 动词

浏览器本身不支持 PUT 和 DELETE 动词。

解决方法:
HTTP 的 Header 中加入一个特殊字段 _method,Spring 中加入 HiddenHttpMethodFilter

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容