简介
从 Spring Boot 项目名称中的 Boot 可以看出来,Spring Boot 的作用在于创建和启动新的基于 Spring 框架的项目。它的目的是帮助开发人员很容易的创建出独立运行和产品级别的基于 Spring 框架的应用。Spring Boot 会选择最适合的 Spring 子项目和第三方开源库进行整合。大部分 Spring Boot 应用只需要非常少的配置就可以快速运行起来。
Spring Boot 包含的特性如下:
创建可以独立运行的 Spring 应用。
直接嵌入 Tomcat 或 Jetty 服务器,不需要部署 WAR 文件。
提供推荐的基础 POM 文件来简化 Apache Maven 配置。
尽可能的根据项目依赖来自动配置 Spring 框架。
提供可以直接在生产环境中使用的功能,如性能指标、应用信息和应用健康检查。
没有代码生成,也没有 XML 配置文件。
添加依赖,pom.xml文件如下:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.et</groupId>
<artifactId>springBoot</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springBoot Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 自动生成sql语句 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- spring boot 整合 mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- spring boot 整合 redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 项目自动刷新 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- spring-boot不支持jsp 添加此配置支持jsp -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- 阿里巴巴连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
</dependencies>
<build>
<finalName>springBoot</finalName>
</build>
</project>
首先是增加了<parent>
spring-boot-starter-parent
包含了大量配置好的依赖管理,在自己项目添加这些依赖的时候不需要写<version>
版本号。
添加了一些spring boot 集成的框架依赖。
添加spring-boot-starter-web依赖
Spring通过添加spring-boot-starter-*
这样的依赖就能支持具体的某个功能。
我们这个示例最终是要实现web功能,所以添加的是这个依赖。
在我们开发过程中,我们需要经常修改,为了避免重复启动项目,我们可以使用spring-boot提供的开发者工具。
<!-- 项目自动刷新 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
添加此依赖修改项目保存后会自动重启你的项目,非常方便
@RestController
这个注解相当于同时添加@Controller
和@ResponseBody
注解
集成mybatis
添加mysql的架包和spring boot集成mybatis的架包
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- spring boot 整合 mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
在application.properties文件里面配置mysql连接池四要素
spring.datasource.url=jdbc:mysql://localhost/et_student
spring.datasource.username=root
spring.datasource.password=LCH
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port=80
server.context-path=
server.session.timeout=30
server.tomcat.uri-encoding=UTF-8
server.port=80 定义该项目的端口,默认的是8080.
server.context-path= 配置上下文路径
server.session.timeout=30 设置session30分钟过期
server.tomcat.uri-encoding=UTF-8 设置编码为UTF-8
mybatis注解动态sql语句
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;
import com.easytop.psm.model.User;
@Mapper
public interface UserDao {
public class SqlProvider {
public String getQueryAllUserSql(Map map) {
Object userName = map.get("userName");
Object gender = map.get("gender");
Object startIndex = map.get("startIndex");
Object limit = map.get("limit");
SQL sql = new SQL();
sql = sql.SELECT("sid id,sname name,sage age,ssex sex").FROM("student");
if (userName != null && !"".equals(userName)) {
sql.WHERE("Sname like '%" + userName + "%'");
}
if (gender != null && !"".equals(gender)) {
sql.AND();
sql.WHERE("Ssex = '" + gender + "'");
}
String sqlStr = sql.toString() + " limit " + startIndex + "," + limit;
return sqlStr;
}
public String getQueryAllUserCountSql(Map map) {
Object userName = map.get("userName");
Object gender = map.get("gender");
SQL sql = new SQL();
sql = sql.SELECT("count(*)").FROM("student");
if (userName != null && !"".equals(userName)) {
sql.WHERE("Sname like '%" + userName + "%'");
}
if (gender != null && !"".equals(gender)) {
sql.AND();
sql.WHERE("Ssex = '" + gender + "'");
}
return sql.toString();
}
}
//调用getQueryAllUserSql方法的sql语句
@SelectProvider(method = "getQueryAllUserSql", type = SqlProvider.class)
public List<User> queryAllUser(@Param("startIndex") Integer startIndex, @Param("limit") Integer limit,
@Param("userName") String userName, @Param("gender") String gender);
@SelectProvider(method = "getQueryAllUserCountSql", type = SqlProvider.class)
public int queryAllUserCount(@Param("userName") String userName, @Param("gender") String gender);
@Select("select sid id,sname name,sage age,ssex sex from student where sid=#{id}")
public User qeruyUser(@Param("id") int id);
}
在接口里定义了内部类SqlProvider,用于写sql语句的方法,apache提供了注解动态sql的方法。
创建SQL sql = new SQL();实例,可以调用动态sql的方法。
使用注解@SelectProvider调用内部类里定义好的sql语句方法,方法传参列表里用map接收接口方法里传入的参数。
druid连接池
添加依赖:
<!-- 阿里巴巴连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
需要将mysql连接四要素给druid
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
/**
* <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
* </bean>
* @author Administrator
*
*/
@Configuration
public class MyConfiguration {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Bean
public DataSource dataSource() {
DruidDataSource dds=new DruidDataSource();
dds.setDriverClassName(driverClassName);
dds.setUrl(url);
dds.setUsername(userName);
dds.setPassword(password);
return dds;
}
@Bean
public ServletRegistrationBean DruidStatView() {
ServletRegistrationBean sr=new ServletRegistrationBean();
sr.setServlet(new StatViewServlet());
List<String> list=new ArrayList<String>();
list.add("/druid/*");
sr.setUrlMappings(list);
return sr;
}
}
添加@Configuration注解
使用@Value注解将配置文件application.properties中的四要素赋值给变量
创建dataSource实例bean
ServletRegistrationBean用于管理监控连接池和sql语句的执行
localhost:端口/druid 访问管理监控连接池的主页面
集成redis
添加依赖
<!-- spring boot 整合 redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.properties文件添加redis的访问ip地址和端口
spring.redis.host=localhost
spring.redis.port=6379
由于StringRedisTemplate并不支持User(自定义对象)的储存到redis中或者取出,所以要将对象序列化再存入到redis中
对象序列化
实现RedisSerializer接口,实现对象序列化
import org.hibernate.type.SerializationException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import com.easytop.psm.model.User;
public class RedisObjectSerializer implements RedisSerializer<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter(User.class.getClassLoader());
static final byte[] EMPTY_ARRAY = new byte[0];
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
}
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}
private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}
注意:在private Converter<byte[], Object> deserializer = new DeserializingConverter(User.class.getClassLoader());创建Converter的时候,要将你的User对象的构造器传入进去,不然Converter就会使用自身的构造器构造user对象,这时候你从redis中取出User对象序列化的时候你的User对象会和序列化后的User对象不匹配,导致无法接收User对象。
创建RedisTemplate的bean实例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.easytop.psm.model.User;
import com.easytop.psm.util.RedisObjectSerializer;
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, User> template = new RedisTemplate<String, User>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}
这时候我们便可以通过@Autowired注解自动装配RedisTemplate<String, User>对象了,
RedisTemplate<String, User>类似于StringRedisTemplate对象,只不过现在我们可以操作对象了
spring-boot 集成 redis ,我们需要在service里面做逻辑处理
@Autowired
private RedisTemplate<String, User> redisTemplate;
public User qeruyUser(int id) {
String userId = "student" + id;
if (redisTemplate.hasKey(userId)) {
return redisTemplate.opsForValue().get(userId);
} else {
User user = userDao.qeruyUser(id);
redisTemplate.opsForValue().set(userId, user);
return user;
}
}
redisTemplate.hasKey(userId)判断redis中是否存在userId这个key键,
如果存在就调用opsForValue().get(userId);方法去redis里面取userId的值,
如果不存在就去数据库里面查询userId的值,并把user存入到redis当中。
jpa自动生成sql语句
添加依赖
<!-- 自动生成sql语句 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
创建实体类student
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Student")
public class Student {
@Id
@Column(nullable = false, name = "Sid")
private String id;
@Column(nullable = false, name = "Sname")
private String name;
@Column(nullable = false, name = "Sage")
private Date age;
@Column(nullable = false, name = "Ssex")
private String sex;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String id, String name, Date age, String sex) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getAge() {
return age;
}
public void setAge(Date age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
@Entity 注解:表示Student是个实体类
@Table(name = "")注解:当类名与数据库表名不一致时,添加此注解,name=数据库表名
@Id注解:表示是主键
@Column(nullable = false, name = "")注解:表示不能为空,然后对象属性要与数据库字段名一致,name=数据库对应的字段名
通过@Column注解设置,包含的设置如下
name:字段名
unique:是否唯一
nullable:是否可以为空
inserttable:是否可以插入
updateable:是否可以更新
columnDefinition: 定义建表时创建此列的DDL
secondaryTable: 从表名。如果此列不建在主表上(默认建在主表),该属性定义该列所在从表的名字。
注解 | 解释 |
@Entity | 声明类为实体或表。 |
@Table | 声明表名。 |
@Basic | 指定非约束明确的各个字段。 |
@Embedded | 指定类或它的值是一个可嵌入的类的实例的实体的属性。 |
@Id | 指定的类的属性,用于识别(一个表中的主键)。 |
@GeneratedValue | 指定如何标识属性可以被初始化,例如自动、手动、或从序列表中获得的值。 |
@Transient | 指定的属性,它是不持久的,即:该值永远不会存储在数据库中。 |
@Column | 指定持久属性栏属性。 |
@SequenceGenerator | 指定在@GeneratedValue注解中指定的属性的值。它创建了一个序列。 |
@TableGenerator | 指定在@GeneratedValue批注指定属性的值发生器。它创造了的值生成的表。 |
@AccessType | 这种类型的注释用于设置访问类型。如果设置@AccessType(FIELD),则可以直接访问变量并且不需要getter和setter,但必须为public。如果设置@AccessType(PROPERTY),通过getter和setter方法访问Entity的变量。 |
@JoinColumn | 指定一个实体组织或实体的集合。这是用在多对一和一对多关联。 |
@UniqueConstraint | 指定的字段和用于主要或辅助表的唯一约束。 |
@ColumnResult | 参考使用select子句的SQL查询中的列名。 |
@ManyToMany | 定义了连接表之间的多对多一对多的关系。 |
@ManyToOne | 定义了连接表之间的多对一的关系。 |
@OneToMany | 定义了连接表之间存在一个一对多的关系。 |
@OneToOne | 定义了连接表之间有一个一对一的关系。 |
@NamedQueries | 指定命名查询的列表。 |
@NamedQuery | 指定使用静态名称的查询。 |
注意:实体类的类名要和表名一致(不一致时可以使用@Table注解),类属性名要与数据库字段名一致(不一致时可以使用@Column注解)
dao层接口
import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.easytop.psm.model.Student;
@Repository
public interface StudentDao extends CrudRepository<Student, Serializable> {
@Query("from Student where sex=:sex")
List<Student> conditionsQueryStudent(@Param("sex") String sex);
}
使用jpa也可以自己写sql语句,不过在这里叫HQL,@Query注解里面添加nativeQuery=true的话,意思是使用原生的sql查询语句,没有添加的话操作时表名写实体类名,字段名写实体类属性名。
:表示传入进来的参数
运行类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestMain {
public static void main(String[] args) throws Exception {
SpringApplication.run(TestMain.class, args);
}
}
@SpringBootApplication
由于大量项目都会在主要的配置类上添加@Configuration,@EnableAutoConfiguration,@ComponentScan
三个注解。因此Spring Boot提供了@SpringBootApplication
注解,该注解可以替代上面三个注解(使用Spring注解继承实现)。