在现在的开发流程中,为了最大程度实现前后端的分离,通常后端接口只提供数据接口,由前端通过Ajax请求从后端获取数据并进行渲染再展示给用户。我们用的最多的方式就是后端会返回给前端一个JSON字符串,前端解析JSON字符串生成JavaScript的对象,然后再做处理。本文就来演示一下Spring boot如何实现这种模式,本文重点会讲解如何设计一个Restful的API,并通过Spring boot来实现相关的API。不过,为了大家更好的了解Restful风格的API,我们先设计一个传统的数据返回接口,这样大家可以对比着来理解。
spring中ref属性与标签
在bean的内部引用另一个bean对象:
使用ref标签对其进行引用:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
<property name="order" value="2"/>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"/>
<!-- 引用外部id为viewResolver的bean -->
<ref bean="viewResolver"/>
</list>
</property>
</bean>
ref属性:用来给一个对象的属性设置值
使用
bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 在spring框架加载时创建 -->
<bean id="borrowDao" class="dao.impl.BorrowDao" primary="true" lazy-init="true">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
ref标签:用来引用另一个bean:
,在spring容器中群钊id为viewResolver的bean对象
History
Spring最早在2003年,由于J2EE过于复杂而被开发出来的。有人认为Spring和Java EE是竞争关系,但Spring更像是对Java EE的补充。Spring整合了一些EE的标准:
Servlet API
WebSocket API
Concurrency Utilities(并发性)
JSON Binding API 简介
Bean Validation(数据校验) 简介
JPA
JMS
Dependency Injection and Common Annotations
Java EE在app开发中的角色在随时间变化。早期的时候,javaEE和Spring开发的应用是部署在application server上的,今天,在Spring Boot的帮助下开发变得友好且更加云端化(devops and cloud-friendly),嵌入Servelet容器,非常容易改变。在Spring Framework5中,一个webflux应用甚至不需要Servlet API并可以运行在不含Servlet容器的server上。
Spring projects目前在逐渐丰富,建立在Spring Framework上的projects有Spring Boot,Spring Security,Spring Data,Spring Cloud,Spring Batch…
Spring的design philosophy
Provide choice at every level 尽可能允许不改动code的情况下变更design
Accommodate diverse perspectives 允许设计的灵活性
Maintain strong backward compatibility 对JDK和第三方库的高兼容性
Care about API design API被设计地简单易用
Set high standards for code quality 注意代码的整洁