新公司的框架为spring boot ,cloud 的一整套微服务框架
其实原先也有想学的想法,正好公司给了一段时间去学。所以这里总结一下。
本篇文章主要总结下关于springboot的一些关键点。
环境:JDK8 STS4.9 MYSQL springBoot1.4.1 maven4.0
springBoot给我的感觉是在springMvc的基础上进一步实现更简单的代码量,配置和部署。
相比而言 如果需要创建一个springMvc ,我需要新建web.xml 配置 application.properties ,pom依赖对应的spring jar 写一个controller 的对应的接口方法
引入tomcat ,部署到tomcat,启动tomcat 才可以
而springBoot 只需要在pom文件里引入他自己封装好的依赖,直接在controller写自己的方法,main函数 运行就可以了
把习惯作为约定的配置,更专注于业务的开发,更少的配置,更低的学习门槛。
缺点是 如果对应spring不熟的话,坑太多了。。自己慢慢排吧。。。
springmvc我就不讲了。下面开始一个最简单的springboot demo
新建maven 项目。
pom里引入相关jar
<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>demo</groupId>
<artifactId>springBootDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springBootDemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<!-- Spring Boot Basic jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot jdbcTemplate jar-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Spring Boot repository jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- Spring Boot actuator jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
最基本的依赖为 继承 spring-boot-starter-parent 为父类,里面封装了所有的springboot 的相关依赖,
下面为对应的 web 依赖,必写,最基本的依赖,如果只写demo的话 到这里 两个依赖就够了
jdbc 依赖 , 和Mybatis 二选一作为连接数据库的做法之一
mybatis依赖,这里的mybatis版本为1.1.1 1.0.0不支持自带分页操作,需要自己实现PageHelper相关插件实现分页
actuator依赖,也就是健康监控,可以在项目启动后通过 /health 查看项目的运行健康状态
下面最基本的依赖写完了 我们就可以写controller了
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Date: 2017年9月15日 上午11:13:03
* @author li
* @desc springBoot 自定义覆盖springBoot的默认约定配置方式
* 主要测试 springboot 连接 Mysql的两种方式
* 1.jdbcTemplate
* 2.继承curdRepository 进行操作
*/
@SpringBootApplication //核心注解为@Configration @ComponentScan @EnableAuthConfigration(SpringBoot独有)
@RestController //@Controller + @ResponseBody 表明该类下所有方法返回值为json
public class SampleConfigController {
//引用外部自定义配置的变量 变量在application.properties 加载外部变量 @Value
@Value("${welcome.string}")
private String welcomeString;
//引用自定义的JDBC 依赖
@Autowired
private JdbcTemplate jdbcTemplate;
//data-jpa mybatis的依赖处理操作
@Autowired
private TypeInfoRepository typeInfoRepository;
@RequestMapping("/")
String home(@RequestParam(value="keyWord", required=false) String keyWord) {
if(null != keyWord) {
return keyWord;
}
return welcomeString;
}
/**
* Date:2017年9月15日下午1:42:30
* @author li
* @desc jdbc调用方法
*/
@RequestMapping("/jdbcTest")
List<Map<String, Object>> getStringFromJdbc() {
String sql = "SELECT ID,TYPE,DESC1 FROM type_info";
return jdbcTemplate.queryForList(sql);
}
/**
*
* Date:2017年9月15日下午2:45:51
* @author li
* @desc jpa调用方式
*/
@RequestMapping("/jpaTest")
List<TypeInfo> getStringFromJpa() {
return typeInfoRepository.findById(15L);
}
/**
*
* Date:2017年9月15日下午2:46:04
* @author li
* @desc 利用Jpa自带的分页 第一个参数为起始位置,第二个参数为获取的数据
*/
@RequestMapping("/jpaTestWithPage")
List<TypeInfo> getStringFromJpaWithPage() {
return typeInfoRepository.findById(15L,new PageRequest(0, 5));
}
/**
*
* Date:2017年9月15日下午2:46:18
* @author li
* @desc 自定义sql实现
*/
@RequestMapping("/getById")
TypeInfo getById() {
return typeInfoRepository.getById(15L);
}
/**
*
* Date:2017年9月19日上午11:07:32
* @author li
* @desc main方法 右键直接启动springBoot
*/
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleConfigController.class, args);
}
}
对应的注释都在代码里,这里涉及到一个外部变量,SpringBoot的变量和数据库配置都在application.properties
这个文件为默认加载文件,默认加载地址为根目录,一般在resource下,
代码:
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
# server
server.port=8080
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
#global variable
welcome.string=hello,${welcome.name}!
welcome.name=boy
#env
#spring.profiles.active=dev
#logger
logging.level.org.springframework.web=INFO
logging.file=./springboot.log
分别指定了数据库的地址
默认加载的tomcat的参数
自定义的一些全局变量,变量直接调用的方式
多环境之间的配置文件的地址 例如dev 的话 在同级目录下会存在一个 application-dev.properties ,具体调用会在部署 启动项目的时候 指定该值 进行动态调用
logger为设置日志文件的一些参数,这里如果没有自定义使用什么日志的话,会自动使用自带的logback
Jdbc不需要dao,mybatis需要相应的mapper,我这里偷懒用的注解,会在启动日志里报一个warn,No MyBatis mapper was found in '[cn.com.gome.SimpleDemo]' package. Please check your configuration. 不影响做操作
现在贴上 mybaties dao层的代码
import javax.transaction.Transactional;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.apache.ibatis.annotations.Select;
import java.lang.Long;
import java.util.List;
/**
*
* Date: 2017年9月15日 下午2:04:34
* @author li
* @desc data-jpa的CrudRepository 会自动根据类型来 进行封装 对应的字段的 find insert等方法
* 第一个参数为返回的对象类型 第二个参数为主键的类型
*/
@Transactional
@Repository
public interface TypeInfoRepository extends CrudRepository<TypeInfo, Long> {
List<TypeInfo> findById(Long id,Pageable pageable);
List<TypeInfo> findById(Long id);
@Select("select * from typeInfo where id = #{id}")
TypeInfo getById(Long id);
}
对应的实体类 也需要进行对应的注解
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "typeInfo")
public class TypeInfo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name="type")
private String type;
@Column(name="desc1")
private String desc1;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc1() {
return desc1;
}
public void setDesc1(String desc1) {
this.desc1 = desc1;
}
}
千万注意 实体类里的 tableName 中间的大小写,会把中间的大写字母自动小写 前面加个_ 如果不想这样 需要自定义继承覆盖它的映射类实现
启动项目,访问localhost:8080
出现 hello,boy! 这是自定义的那个全局变量
Demo完成。