Java Web系列:Spring Boot 基础
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 基础的更多相关文章
- 传统Java Web(非Spring Boot)、非Java语言项目接入Spring Cloud方案
技术架构在向spring Cloud转型时,一定会有一些年代较久远的项目,代码已变成天书,这时就希望能在不大规模重构的前提下将这些传统应用接入到Spring Cloud架构体系中作为一个服务以供其它项 ...
- 传统Java Web(非Spring Boot)、非Java语言项目接入Spring Cloud方案--temp
技术架构在向spring Cloud转型时,一定会有一些年代较久远的项目,代码已变成天书,这时就希望能在不大规模重构的前提下将这些传统应用接入到Spring Cloud架构体系中作为一个服务以供其它项 ...
- Java Web系列:JDBC 基础
ADO.NET在Java中的对应技术是JDBC,企业库DataAccessApplicationBlock模块在Java中的对应是spring-jdbc模块,EntityFramework在Java中 ...
- Java Web系列:Hibernate 基础
从以下5个方面学习hibernate ORM. (1)配置文件:hibernate.cfg.xml XML文件和hibernate.properties属性文件 (2)实体映射:1对多.多对多 (3) ...
- Java Web系列:Spring Security 基础
Spring Security虽然比JAAS进步很大,但还是先天不足,达不到ASP.NET中的认证和授权的方便快捷.这里演示登录.注销.记住我的常规功能,认证上自定义提供程序避免对数据库的依赖,授权上 ...
- Spring Boot 基础,理论,简介
Spring Boot 基础,理论,简介 1.SpringBoot自动装配 1.1 Spring装配方式 1.2 Spring @Enable 模块驱动 1.3 Spring 条件装配 2.自动装配正 ...
- Spring Boot 基础
Spring Boot 基础 Spring Boot 项目(参考1) 提供了一个类似ASP.NET MVC的默认模板一样的标准样板,直接集成了一系列的组件并使用了默认的配置.使用Spring Boot ...
- spring boot基础学习教程
Spring boot 标签(空格分隔): springboot HelloWorld 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新 ...
- spring boot基础 入门
spring boot基础 spring boot 的简单搭建 spring boot 的基本用法 spring boot 基本用法 自动配置 技术集成 性能监控 源码解析 工程的构建 创建一个mav ...
- 第64节:Java中的Spring Boot 2.0简介笔记
Java中的Spring Boot 2.0简介笔记 spring boot简介 依赖java8的运行环境 多模块项目 打包和运行 spring boot是由spring framework构建的,sp ...
随机推荐
- 50个jquery代码片段(转)
本文会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助 ...
- 02_嵌套矩形(DAG最长路问题)
来源:刘汝佳<算法竞赛入门经典--训练指南> P60 问题2: 问题描述:有n个矩形,每个矩形可以用两个整数a,b描述,表示它们的长和宽.矩形X(a,b)可以嵌套在矩形Y(c,d)中的条件 ...
- Merge Two Sorted Lists
Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/ Merge two sorted linked ...
- 初识selenium-grid
什么是selenium-grid,官方解释:takes Selenium Remote Control to another level by running tests on many server ...
- 【ASP.NET 基础】Page类和回调技术
Page 类有一个 IsPostBack 属性,这个属性用来指示当前页面是第一次加载还是响应了页面上某个控件的服务器事件导致回发而加载. 1.asp.net页面的声明周期 asp.net页面运行的时候 ...
- 二分法 codevs 1432 总数统计
codevs 1432 总数统计 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description 给出n个数,统计两两之和小于k的方 ...
- codeforces 477B B. Dreamoon and Sets(构造)
题目链接: B. Dreamoon and Sets time limit per test 1 second memory limit per test 256 megabytes input st ...
- java 15 - 8 集合框架(并发修改异常的产生原因以及解决方案)
问题? 我有一个集合,如下,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现. 面试题: Concu ...
- BZOJ 3572: [Hnoi2014]世界树
BZOJ 3572: [Hnoi2014]世界树 标签(空格分隔): OI-BZOJ OI-虚数 OI-树形dp OI-倍增 Time Limit: 20 Sec Memory Limit: 512 ...
- [原创]CI持续集成系统环境--Gitlab+Gerrit+Jenkins完整对接
近年来,由于开源项目.社区的活跃热度大增,进而引来持续集成(CI)系统的诞生,也越发的听到更多的人在说协同开发.敏捷开发.迭代开发.持续集成和单元测试这些拉风的术语.然而,大都是仅仅听到在说而已,国内 ...