SpringBoot的重要特性

1、Web特性

Spring Boot 提供了spring-boot-starter-web来为Web开发予以支持,spring-boot-starter-web为咱们提供了嵌入的Tomcat以及SpringMVC的依赖,用起来很方便。另外,咱们这里还要用到模板引擎,咱们作web开发可选的模板引擎仍是挺多的,这里我主要使用Thymeleaf做为模板引擎。
事实上,Spring Boot提供了大量的模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,在 提供的这么多中它推荐使用Thymeleaf。 

一、自定义Filter

咱们经常在项目中会使用filters用于录调用日志、排除有XSS威胁的字符、执行权限验证等等。Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,而且咱们能够自定义Filter。css

两个步骤:前端

实现Filter接口,实现Filter方法
添加@Configuration 注解,将自定义Filter加入过滤链
@Configuration
public class WebConfiguration {
@Bean
public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}

@Bean
public FilterRegistrationBean testFilterRegistration() {vue

FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
}

public class MyFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}java

@Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest) srequest;
System.out.println("this is MyFilter,url :"+request.getRequestURI());
filterChain.doFilter(srequest, sresponse);
}mysql

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
}jquery

二、关于controller

  • @RestController ---- json数据返回
  • @Controller ---- 普通页面开发

三、thymeleaf模板

Spring boot 推荐使用thymeleaf模板来代替jsp,thymeleaf模板究竟是什么来头呢?web

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。相似JSP,Velocity,FreeMaker等,它也能够轻易的与Spring MVC等Web框架进行集成做为Web应用的模板引擎。
与其它模板引擎相比,Thymeleaf最大的特色是可以直接在浏览器中打开并正确显示模板页面,而不须要启动整个Web应用。spring

咱们已经习惯使用了什么 velocity,FreMaker,beetle之类的模版,那么thymeleaf到底好在哪里呢? Thymeleaf是不同凡响的,由于它使用了天然的模板技术。这意味着Thymeleaf的模板语法并不会破坏文档的结构,
模板依旧是有效的XML文档, 模板还能够用做工做原型.
Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。 sql

下面的代码示例分别使用Velocity、FreeMarker与Thymeleaf打印出一条消息:
Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>
注意,因为Thymeleaf使用了XML DOM解析器,所以它并不适合于处理大规模的XML文件。数据库

URL
URL在Web应用模板中占据着十分重要的地位,须要特别注意的是Thymeleaf对于URL的处理是经过语法@{…}来处理的。Thymeleaf支持绝对路径URL:

<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

条件求值
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

for循环
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

页面即原型
在Web开发过程当中前端工程师与后端工程师须要分工协做做,传统Java Web开发过程当中,前端工程师和后端工程师同样,也须要安装一套完整的开发环境,
而后在各种Java IDE中修改模板、静态资源文件,启动/重启/从新加载应用服务器,刷新页面查看最终效果。

但实际上前端工程师的职责更多应该关注于页面自己而非后端,
使用JSP,Velocity等传统的Java模板引擎很难作到这一点,由于它们必须在应用服务器中渲染完成后才能在浏览器中看到结果,
而Thymeleaf从根本上颠覆了这一过程,经过属性进行模板渲染不会引入任何新的浏览器不能识别的标签,例如JSP中的,不会在Tag内部写表达式。
整个页面直接做为HTML文件用浏览器打开,几乎就能够看到最终的效果,这大大解放了前端工程师的生产力,它们的最终交付物就是纯的HTML/CSS/JavaScript文件。

2、其余应用特性

一、使用自定义配置

配置在application.properties中
com.neo.title=你好,朋友
com.neo.description=生活充满了无奈

自定义配置类
@Component
public class NeoProperties {
@Value("${com.neo.title}")
private String title;
@Value("${com.neo.description}")
private String description;

//省略getter settet方法

}

二、配置日志输出的地址和输出级别

logging.path=/user/local/log logging.level.com.favorites=DEBUG logging.level.org.springframework.web=INFO logging.level.org.hibernate=ERROR 

path为本机的log地址,logging.level  后面能够根据包路径配置不一样资源的log级别

三、数据库操做 - jpa

这里重点讲述mysql、spring data jpa的使用,其中mysql 就不用说了你们很熟悉,jpa是利用Hibernate生成各类自动化的sql,若是只是简单的增删改查,基本上不用手写了,spring内部已经帮你们封装实现了。

下面简单介绍一下如何在spring boot中使用

3.一、添加jar包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

3.二、添加配置文件

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
其实这个hibernate.hbm2ddl.auto参数的做用主要用于:自动建立|更新|验证数据库表结构,有四个值:

create: 每次加载hibernate时都会删除上一次的生成的表,而后根据你的model类再从新来生成新表,哪怕两次没有任何改变也要这样执行,这就是致使数据库表数据丢失的一个重要缘由。
create-drop :每次加载hibernate时根据model类生成表,可是sessionFactory一关闭,表就自动删除。
update:最经常使用的属性,第一次加载hibernate时根据model类会自动创建起表的结构(前提是先创建好数据库),之后加载hibernate时根据 model类自动更新表结构,即便表结构改变了但表中的行仍然存在不会删除之前的行。要注意的是当部署到服务器后,表结构是不会被立刻创建起来的,是要等 应用第一次运行起来后才会。
validate :每次加载hibernate时,验证建立数据库表结构,只会和数据库中的表进行比较,不会建立新表,可是会插入新值。
dialect 主要是指定生成表名的存储引擎为InneoDB show-sql 是否打印出自动生产的SQL,方便调试的时候查看

3.三、添加实体类和Dao

@Entity
public class User implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;

//省略getter settet方法、构造方法

}
dao只要继承JpaRepository类就能够,几乎能够不用写方法,还有一个特别有尿性的功能很是赞,就是能够根据方法名来自动的生产SQL,好比findByUserName 会自动生产一个以 userName 为参数的查询方法,好比 findAlll 自动会查询表里面的全部数据,好比自动分页等等。。

Entity中不映射成列的字段得加@Transient 注解,不加注解也会映射成列

public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);

3.四、运行测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class UserRepositoryTests {

@Autowired
private UserRepository userRepository;

@Test
public void test() throws Exception {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
String formattedDate = dateFormat.format(date);

userRepository.save(new User("aa1", "aa@126.com", "aa", "aa123456",formattedDate));
userRepository.save(new User("bb2", "bb@126.com", "bb", "bb123456",formattedDate));
userRepository.save(new User("cc3", "cc@126.com", "cc", "cc123456",formattedDate));

Assert.assertEquals(9, userRepository.findAll().size());
Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "cc@126.com").getNickName());
userRepository.delete(userRepository.findByUserName("aa1"));
}

}
当让 spring data jpa 还有不少功能,好比封装好的分页,能够本身定义SQL,主从分离等等

3、软件工程

一、 gradle构建

Gradle 构建工具

spring 项目建议使用Gradle进行构建项目,相比maven来说 Gradle更简洁,并且gradle更时候大型复杂项目的构建。gradle吸取了maven和ant的特色而来,不过目前maven仍然是Java界的主流,你们能够先了解了解。

一个使用gradle配置的项目

buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}

apply plugin: 'java' //添加 Java 插件, 代表这是一个 Java 项目
apply plugin: 'spring-boot' //添加 Spring-boot支持
apply plugin: 'war' //添加 War 插件, 能够导出 War 包
apply plugin: 'eclipse' //添加 Eclipse 插件, 添加 Eclipse IDE 支持, Intellij Idea 为 "idea"

war {
baseName = 'favorites'
version = '0.1.0'
}

sourceCompatibility = 1.7 //最低兼容版本 JDK1.7
targetCompatibility = 1.7 //目标兼容版本 JDK1.7

repositories { // Maven 仓库
mavenLocal() //使用本地仓库
mavenCentral() //使用中央仓库
maven { url "http://repo.spring.io/libs-snapshot" } //使用远程仓库
}

dependencies { // 各类 依赖的jar包
compile("org.springframework.boot:spring-boot-starter-web:1.3.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf:1.3.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-data-jpa:1.3.6.RELEASE")
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
compile("org.springframework.boot:spring-boot-devtools:1.3.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-test:1.3.6.RELEASE")
compile 'org.webjars.bower:bootstrap:3.3.6'
compile 'org.webjars.bower:jquery:2.2.4'
compile("org.webjars:vue:1.0.24")
compile 'org.webjars.bower:vue-resource:0.7.0'

}

bootRun {
addResources = true
}

二、WebJars

WebJars是一个很神奇的东西,可让你们以jar包的形式来使用前端的各类框架、组件。
什么是WebJars?WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。

为何使用
咱们在开发Java web项目的时候会使用像Maven,Gradle等构建工具以实现对jar包版本依赖管理,以及项目的自动化管理,
可是对于JavaScript,Css等前端资源包,咱们只能采用拷贝到webapp下的方式,这样作就没法对这些资源进行依赖管理。
那么WebJars就提供给咱们这些前端资源的jar包形势,咱们就能够进行依赖管理。

如何使用一、WebJars主官网 查找对应组件,好比Vuejs<dependency> <groupId>org.webjars.bower</groupId> <artifactId>vue</artifactId> <version>1.0.21</version></dependency>二、页面引入<link th:href="@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}" rel="stylesheet"></link>就能够正常使用了!

相关文章
相关标签/搜索