笔者最近在总结一个 Spring Boot实战系列,以方便未来查找和公司内部培训用途。css
SpringBoot是由Pivotal团队在2013年开始研发、2014年4月发布第一个版本的全新开源的轻量级框架。它基于Spring4.0设计,不只继承了Spring框架原有的优秀特性,并且还经过简化配置来进一步简化了Spring应用的整个搭建和开发过程。另外SpringBoot经过集成大量的框架使得依赖包的版本冲突,以及引用的不稳定性等问题获得了很好的解决。html
其主要的优点以下:前端
Springboot官网目前推荐的版本是2.1.7. 若是是刚开始使用Springboot,那么从2.X开始无疑是最好的选择。java
当下大多数公司的生产环境的版本应该是1.X系列。官方最后的1.X版本落在1.5.22.mysql
https://spring.io/blog/2019/08/06/it-is-time-goodbye-spring-boot-1-xweb
Eclipse里面新建项目,选择Spring Starter Project模板,经过向导点击下一步,项目命名为ProductApp0最后选择2.1.7版本。spring
在resources文件夹里面建立static,templates,public/error的文件夹。sql
application.properties:自动生成,用于配置项目运行所需的配置数据。数据库
static:用于存放静态资源,里面继续建立子文件夹js,css,image。
public/error: 用于存放相似404.html,5xx.html等文件apache
templates:用于存放模板文件,使用官方推荐的Thymeleaf
demo下面建立该项目用到的几个文件夹,config,store,model,controller
项目文件夹分布架构大体以下:
该项目具备三个功能,分别向前端返回一个字符串,一个对象,以及一个集合。
4.1 Pom.xml里面主要添加的包是web, jdbc,jpa, mysql driver,fastjson.结构以下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- springboot,jpa 整合包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql 驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--根据MySQL server 版本实际状况变更 -->
<version>8.0.17</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<!-- 引入FastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
4.2 该示例须要用到一张表,结构以下:
CREATE TABLE `book` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `Category` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `Price` decimal(18,2) NOT NULL, `Publish_Date` date NOT NULL, `Poster` varchar(45) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8
4.3 使用Spring-data-jpa访问数据库,分别在model,store文件夹里面里面建立Book 类,BookRepository接口。
@Entity public class Book implements Serializable { private static final long serialVersionUID = -3123479062966697145L; @Id @Column private Integer id; @Column private String name; @Column private String category; @Column private Double price; @Column @JSONField(format="yyyy-MM-dd") private Date publish_date; @Column private String poster; } //省略getter,setter方法
public interface BookRepository extends JpaRepository<Book,Integer> { }
4.4. 引入fastjson,须要添加一个配置类
@Configuration public class JSONWebConfig { @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter); } }
4.5 在controller文件夹里面建立HelloController class以下,
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private BookRepository bookRepository; @GetMapping("/test") public String test() { return "My first springboot web application!"; } @GetMapping("/findOne") public Book findOne() throws NotFoundException { int id=1; Optional<Book> book = this.bookRepository.findById(id); if(book.isPresent()) { return book.get(); } else { throw new NotFoundException("Not found..."); } } @GetMapping("/findAll") public List<Book> findAll() { List<Book> books = this.bookRepository.findAll(); return books; } }
说明:
4.6 application.properties文件内容以下:
# DB connection configuration spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC spring.datasource.username=*** spring.datasource.password=****** # JPA configuration spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
4.7 程序入口点在main函数
@SpringBootApplication public class ProductApp0Application { public static void main(String[] args) { SpringApplication.run(ProductApp0Application.class, args); } }
@SpringBootApplication是Spring Boot的核心注解,是一个组合注解,用于启动类上。包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让spring Boot扫描到Configuration类并把它加入到程序上下文。
选中项目,右键选择Debug As或Run As菜单,先点击Maven clean,后点击Maven install。
编译无错误后,点击Spring Boot App运行项目。
浏览器输入如下地址,查看结果。
http://localhost:8080/hello/test
http://localhost:8080/hello/findOne
http://localhost:8080/hello/findAll
5.1通常来讲打成jar或者war包,eclipse默认生成jar包。在项目里面的target文件夹里面。 运行程序则用下面的命令,
java -jar ProductApp0-0.0.1-SNAPSHOT.jar
5.2.1 SpringbootApplication 类继承 SpringBootServletInitializer 并重写 configure 方法,以下:
@SpringBootApplication public class ProductApp0Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(ProductApp0Application.class); } public static void main(String[] args) { SpringApplication.run(ProductApp0Application.class, args); } }
5.2.2 在pom.xml里面添加一行,跟在<description>标签后面,
<groupId>com.example</groupId>
<artifactId>ProductApp0</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ProductApp0</name>
<description>Demo project for Spring Boot</description>
<packaging>war</packaging>
Eclipse里面点击Maven clean, Maven install,最终在target文件夹里面生成以下:
复制 war包到tomcat/webapps文件夹,建议重名为home.war. 而后启动tomcat/bin文件夹里面的startup.bat
浏览器里面输入以下地址,查看结果
http://localhost:8080/home/hello/test