Spring Boot 项目(参考1) 提供了一个类似ASP.NET MVC的默认模板一样的标准样板,直接集成了一系列的组件并使用了默认的配置。使用Spring Boot 不会降低学习成本,甚至增加了学习成本,但显著降低了使用成本并提高了开发效率。如果没有Spring基础不建议直接上手。

1.基础项目

这里只关注基于Maven的项目构建,使用Spring Boot CLI命令行工具和Gradle构建方式请参考官网。

(1)创建项目:

创建类型为quickstart的Maven项目,删除默认生成的.java文件保持默认的Maven目录即可。

(2)修改/pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

(3)添加/src/main/sample/controller/HomeController.java文件:

 package simple.controller;

 import org.springframework.web.bind.annotation.*;

 @RestController
public class HomeController { @RequestMapping("/")
public String index() {
return "Hello World!";
}
}

(4)添加/src/main/sample/Application.java文件:

 package simple;

 import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import simple.controller.*; @EnableAutoConfiguration
public class Application { public static void main(String[] args) throws Exception {
SpringApplication.run(new Object[] { Application.class, HomeController.class }, args);
} }

在浏览器中输入http://localhost:8080/,即可直接看到"Hello World"运行结果。

2. 添加数据访问支持

(1)修改pom,添加spring-boot-starter-data-jpa和h2依赖:

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>

如果需要在控制台查看生成SQL语句,可以添加/src/main/resources/application.properties

 spring.h2.console.enabled=true
logging.level.org.hibernate.SQL=debug

(2)添加实体

添加User、Role、Category和Post实体。

User:

 package simple.domain;

 import java.util.*;

 import javax.persistence.*;

 @Entity
public class User {
@Id
@GeneratedValue
private Long id; private String userName; private String password; private String Email; @javax.persistence.Version
private Long Version; @ManyToMany(cascade = CascadeType.ALL)
private List<Role> roles = new ArrayList<Role>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getEmail() {
return Email;
} public void setEmail(String email) {
Email = email;
} public List<Role> getRoles() {
return roles;
} public void setRoles(List<Role> roles) {
this.roles = roles;
} public Long getVersion() {
return Version;
} public void setVersion(Long version) {
Version = version;
}
}

Role:

 package simple.domain;

 import java.util.*;

 import javax.persistence.*;

 @Entity
public class Role {
@Id
@GeneratedValue
private Long id; private String roleName; @ManyToMany(cascade = CascadeType.ALL)
private List<User> users = new ArrayList<User>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getRoleName() {
return roleName;
} public void setRoleName(String roleName) {
this.roleName = roleName;
} public List<User> getUsers() {
return users;
} public void setUsers(List<User> users) {
this.users = users;
}
}

Category:

 package simple.domain;

 import java.util.*;

 import javax.persistence.*;

 @Entity
public class Category {
@Id
@GeneratedValue
private Long id; private String Name; @OneToMany
private List<Post> posts = new ArrayList<Post>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return Name;
} public void setName(String name) {
Name = name;
} public List<Post> getPosts() {
return posts;
} public void setPosts(List<Post> posts) {
this.posts = posts;
}
}

Post:

 package simple.domain;

 import java.util.*;

 import javax.persistence.*;

 @Entity
public class Post {
@Id
@GeneratedValue
private Long id; private String Name; private String Html; private String Text; private Date CreateAt; @ManyToOne
private Category category; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return Name;
} public void setName(String name) {
Name = name;
} public String getHtml() {
return Html;
} public void setHtml(String html) {
Html = html;
} public String getText() {
return Text;
} public void setText(String text) {
Text = text;
} public Date getCreateAt() {
return CreateAt;
} public void setCreateAt(Date createAt) {
CreateAt = createAt;
} public Category getCategory() {
return category;
} public void setCategory(Category category) {
this.category = category;
}
}

(3)添加资源库

添加UserRepository、RoleRepository、CategoryRepository和PostRepository接口,无需实现。

UserRepository:

 package simple.repository;

 import org.springframework.data.repository.*;

 import simple.domain.*;

 public interface UserRepository extends CrudRepository<User, Long> {

 }

RoleRepository

 package simple.repository;

 import org.springframework.data.repository.*;

 import simple.domain.*;

 public interface RoleRepository extends CrudRepository<Role, Long> {

 }

CategoryRepository

 package simple.repository;

 import org.springframework.data.repository.*;

 import simple.domain.*;

 public interface CategoryRepository extends CrudRepository<Category, Long> {

 }

PostRepository

package simple.repository;

import org.springframework.data.repository.*;

import simple.domain.*;

public interface PostRepository extends CrudRepository<User, Long> {

}

(4)在控制器中注入资源库接口

 package simple.controller;

 import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*; import simple.repository.*; @RestController
public class HomeController { private UserRepository userRepository;
private RoleRepository roleRepository;
private CategoryRepository categoryRepository;
private PostRepository postReppository; @Autowired
public HomeController(UserRepository userRepository, RoleRepository roleRepository,
CategoryRepository categoryRepository, PostRepository postReppository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.categoryRepository = categoryRepository;
this.postReppository = postReppository;
} @RequestMapping("/")
public long index() {
return userRepository.count();
}
}

使用事务时在方法上应用注解@Transactional

3.添加验证和授权支持

(1)添加spring-boot-starter-security依赖

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
</project>

(2)修改Application.java

 package simple;

 import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import simple.controller.*; @EnableAutoConfiguration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class Application { public static void main(String[] args) throws Exception {
SpringApplication.run(new Object[] { Application.class, HomeController.class }, args);
} @Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
return new MyWebSecurityConfigurer();
} public static class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/account**", "/admin**").authenticated();
http.formLogin().usernameParameter("userName").passwordParameter("password").loginPage("/login")
.loginProcessingUrl("/login").successHandler(new SavedRequestAwareAuthenticationSuccessHandler())
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/");
http.rememberMe().rememberMeParameter("rememberMe"); }
}
}

访问http://localhost:8080/account会自动跳转到login登录页。Spring Security的具体使用前文已有所述。

参考:

(1)https://github.com/spring-projects/spring-boot

(2)http://projects.spring.io/spring-boot/

(3)https://github.com/qibaoguang/Spring-Boot-Reference-Guide/blob/master/SUMMARY.md

Java Web系列:Spring Boot 基础的更多相关文章

  1. 传统Java Web(非Spring Boot)、非Java语言项目接入Spring Cloud方案

    技术架构在向spring Cloud转型时,一定会有一些年代较久远的项目,代码已变成天书,这时就希望能在不大规模重构的前提下将这些传统应用接入到Spring Cloud架构体系中作为一个服务以供其它项 ...

  2. 传统Java Web(非Spring Boot)、非Java语言项目接入Spring Cloud方案--temp

    技术架构在向spring Cloud转型时,一定会有一些年代较久远的项目,代码已变成天书,这时就希望能在不大规模重构的前提下将这些传统应用接入到Spring Cloud架构体系中作为一个服务以供其它项 ...

  3. Java Web系列:JDBC 基础

    ADO.NET在Java中的对应技术是JDBC,企业库DataAccessApplicationBlock模块在Java中的对应是spring-jdbc模块,EntityFramework在Java中 ...

  4. Java Web系列:Hibernate 基础

    从以下5个方面学习hibernate ORM. (1)配置文件:hibernate.cfg.xml XML文件和hibernate.properties属性文件 (2)实体映射:1对多.多对多 (3) ...

  5. Java Web系列:Spring Security 基础

    Spring Security虽然比JAAS进步很大,但还是先天不足,达不到ASP.NET中的认证和授权的方便快捷.这里演示登录.注销.记住我的常规功能,认证上自定义提供程序避免对数据库的依赖,授权上 ...

  6. Spring Boot 基础,理论,简介

    Spring Boot 基础,理论,简介 1.SpringBoot自动装配 1.1 Spring装配方式 1.2 Spring @Enable 模块驱动 1.3 Spring 条件装配 2.自动装配正 ...

  7. Spring Boot 基础

    Spring Boot 基础 Spring Boot 项目(参考1) 提供了一个类似ASP.NET MVC的默认模板一样的标准样板,直接集成了一系列的组件并使用了默认的配置.使用Spring Boot ...

  8. spring boot基础学习教程

    Spring boot 标签(空格分隔): springboot HelloWorld 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新 ...

  9. spring boot基础 入门

    spring boot基础 spring boot 的简单搭建 spring boot 的基本用法 spring boot 基本用法 自动配置 技术集成 性能监控 源码解析 工程的构建 创建一个mav ...

  10. 第64节:Java中的Spring Boot 2.0简介笔记

    Java中的Spring Boot 2.0简介笔记 spring boot简介 依赖java8的运行环境 多模块项目 打包和运行 spring boot是由spring framework构建的,sp ...

随机推荐

  1. 在VS项目中使用SVN版本号作为编译版本号

    在实际项目中(特别是作为产品的项目),版本号是必不可少的一部分.版本号的规则也有许多种,在此不讨论具体的编码规范.对于迭代的产品,版本繁多,特别是有多个实施项目所使用产品的版本不同(基于定制需求)时, ...

  2. 烂泥:LVM学习之LVM基础

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 有关LVM的好处我就不在此多介绍了,有空的话自己可以去百度百科中看看.我们在此之进行LVM的相关操作,以及命令的学习. 要想使系统支持LVM,我们必须安 ...

  3. mysql日志类型

    在MySQL中共有4中日志:错误日志.二进制日志.查询日志和慢查询日志 一.错误日志 错误日志名 host_name.err,并默认在参数DATADIR指定的目录中写入日志文件.可使用 --log-e ...

  4. UVALive - 2965 Jurassic Remains (LA)

    Jurassic Remains Time Limit: 18000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu [Sub ...

  5. Azure CDN 启用HTTPS

    默认情况下,订阅里的CDN不支持HTTPS 需要联系21v,提交工单告知订阅号,由后台为订阅启用CDN的HTTPS功能. 然后就可以在创建CDN时选到HTTPS的选项了.

  6. 用SecureCRT在windows和CentOS间上传下载文件

    安装lrzsz: # yum -y install lrzsz 现在就可以正常使用rz.sz命令上传.下载数据了 配置SecureCRT的session选项的SFTP标签页和X/Y/Zmodem中的目 ...

  7. C++ inline

    内联函数相对于宏的区别和优点: 宏是在预处理时进行的机械替换,内联是在编译时进行的.内联函数是真正的函数,只是在调用时,没有调用开销,像宏一样进行展开.内联函数会进行参数匹配检查,相对于带参数的宏有很 ...

  8. HDU 1576 A/B【扩展欧几里德】

    设A/B=x,则A=Bx n=A%9973=A-9973*y=Bx-9973*y 用扩展欧几里德求解 #include<stdio.h> #include<string.h> ...

  9. 首次安装Pycharm出现No Python interpreter selected解决方法

    刚装完Pycharm,新建Project的时候,出现了No Python interpreter selected.网上的教程里path interpret栏里应该选中python.exe,但是我搜遍 ...

  10. .Net core环境准备

    .Net core 出来有段日子了,在跨平台上迈出了坚实的一步,尽管如此身边还是有很多人都转向了Java阵营.抛开语言之争,在.net平台上工作多年,还是有必要了解下新推出的技术,没准有朝一日就用上了 ...