Spring Boot:其最主要作用就是帮助开发人员快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让开发人员关注业务而非配置。
这三步跟上面一样的
springboot支持二种类型的配置文件
properties
属性配置文件yaml
配置文件(好像后续用这个比较多,写起来方便)配置文件必须放置在项目的类加载目录下, 并且名字必须是application
在 resource
文件夹下面新建 application.properties
配置文件
spring.jdbc.datasource.driverClassName=com.mysql.jdbc.driver
spring.jdbc.datasource.url=jdbc:mysql:///springboot_01
spring.jdbc.datasource.username=root
spring.jdbc.datasource.password=root
新建 properties
包,创建类 DataSourceProperties
package com.atguigu.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class DataSourceProperties {
@Value("${spring.jdbc.datasource.driverClassName}")
// 注入属性,把application.properties里的spring.jdbc.datasource.driverClassName对应的值,注入到driverClassName中
private String driverClassName;
@Value("${spring.jdbc.datasource.url}")
private String url;
@Value("${spring.jdbc.datasource.username}")
private String username;
@Value("${spring.jdbc.datasource.password}")
private String password;
// 生成get set 和 toString方法
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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;
}
@Override
public String toString() {
return "DataSourceProperties{" +
"driverClassName='" + driverClassName + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
在 controller
的 hello
方法中获取配置信息
package com.atguigu.controller;
import com.atguigu.properties.DataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloSpringBoot {
@Autowired
private DataSourceProperties dataSourceProperties;
@RequestMapping("/hello")
public String hello(){
System.out.println("dataSourceProperties = " + dataSourceProperties);
return "Hello Spring Boot Self !";
}
}
语法 :
1.数据结构用树形结构呈现,通过缩进来表示层级,
2.连续的项目通过减号 ” - ” 来表示
3.键值结构里面的key/value对用冒号 ” : ” 来分隔。
4.YAML配置文件的扩展名是yaml 或 yml
只需要把properties
改成yaml
文件即可
spring:
jdbc:
datasource:
username: root
# username: 有两个值的写法
# - root
# - root2
password: root
driverClassName: com.mysql.jdbc.driver.yaml
url: jdbc:mysql:///springboot_01/yaml
spring boot项目中允许使用多个YAML配置文件。
这些文件名称必须为application-***.yml
,并且在application.yml
中激活。
demo案例
创建application-dev.yml
文件
spring:
jdbc:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql:///springboot
username: root
password: root
创建application-pro.yml
文件
spring:
jdbc:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql:///business
username: business
password: business
在 application.yml
文件中添加如下配置
激活配置文件
spring:
profiles:
active: dev // 修改active的值(dev/pro)可以切换配置文件
properties
和yml
文件都存在,不存在spring.profiles.active
设置,如果有重叠属性,默认以properties优先
。spring.profiles.active
,并且有重叠属性,以active设置优先
。@ConfigurationProperties是SpringBoot提供的重要注解, 他可以将一些配置属性批量注入到bean对象。
application.yml配置文件
spring:
jdbc:
datasource:
driverClassName: com.mysql.jdbc.driver
url: jdbc:mysql:///springboot_01
username: root
password: root
DataSourceProperties.java
public class DataSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
// 省略getter和setter.....
}
@Component
public class DataSourceProperties {
@Value("${spring.jdbc.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.jdbc.datasource.url}")
private String url;
@Value("${spring.jdbc.datasource.username}")
private String username;
@Value("${spring.jdbc.datasource.password}")
private String password;
// 省略getter和setter.....
}
第一步:批量注入
package com.atguigu.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "spring.jdbc.datasource")
public class DataSourceProperties2 {
private String driverClassName;
private String url;
private String username;
private String password;
// 省略getter和setter.....
}
1、在类上通过
@ConfigurationProperties
注解声明该类要读取属性配置
2、prefix="spring.jdbc.datasource"
读取属性文件中前缀为spring.jdbc.datasource的值。前缀和属性名称和配置文件中的key必须要保持一致才可以注入成功
3、Spring Boot默认读取application.properties
属性文件
第二步:开启@ConfigurationProperties注解使用
@EnableConfigurationProperties(DataSourceProperties2.class)
@RestController
public class HelloSpringBoot2 {
@Autowired
private DataSourceProperties2 dataSourceProperties2;
@RequestMapping("/hello2")
public String hello(){
System.out.println("dataSourceProperties2 = " + dataSourceProperties2);
return "Hello Spring Boot Self !";
}
}
package com.atguigu;
import org.springframework.boot.SpringApplication;
import org.springframework.b oot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootMVCApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMVCApplication.class,args);
}
}
public class User {
private String username ;
private String password ;
private Integer age ;
private String sex ;
// ...省略了getter和setter,toString方法
}
package com.atguigu.controller;
import com.atguigu.entities.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/findAll")
public List<User> findAll(){
//查询所有
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setUsername("杨过");
user1.setPassword("123456");
user1.setAge(18);
user1.setSex("男");
User user2 = new User();
user2.setUsername("小龙女");
user2.setPassword("654321");
user2.setAge(18);
user2.setSex("女");
User user3 = new User();
user3.setUsername("尹志平");
user3.setPassword("666666");
user3.setAge(19);
user3.setSex("女");
users.add(user1);
users.add(user2);
users.add(user3);
return users ;
}
}
访问:http://localhost:8080/user/findAll
现在使用Spring Boot做开发 , 项目中没有webapp目录
在springboot中有一个叫做ResourceProperties的类,里面就定义了静态资源的默认查找路径。
默认的静态资源路径为:
我们只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理。
我们习惯会把静态资源放在classpath:/static/ 目录下。
通过http://localhost:8080/index.html
直接访问静态资源。
SpringBoot没有XML配置文件 , 所以 需要借助一个WebMvcConfigurer类帮助我们注册拦截器 , 实现拦截器的具体步骤如下 :
package com.atguigu.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MySpringMVCInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle---处理请求之前调用");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle---处理请求之后渲染视图之前调用");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion---渲染视图之后调用");
}
}
注册拦截器
package com.atguigu.config;
import com.atguigu.interceptor.MySpringMVCInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootConfiguration //声明当前类是一个配置类
public class MyMVCConfig implements WebMvcConfigurer {
// 注入我们创建的拦截器
@Autowired
private MySpringMVCInterceptor mySpringMVCInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(mySpringMVCInterceptor)
.addPathPatterns("/user/findAll")//配置拦截的请求
.excludePathPatterns("/index.html");
}
}
JPA是Java Persistence API的简称,中文名Java持久层API。
持久层(数据访问层),其功能主要是负责数据库的访问。简单地说就是实现对数据表的增删改查等操作。
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.2.RELEASEversion>
<relativePath/>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
dependencies>
logging:
level:
com.atguigu.dao: debug # 配置日志
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
database: mysql
show-sql: true
generate-ddl: true
hibernate:
ddl-auto: update
naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
server:
port: 18081
注意:Mysql8.x版本,连接时url需要指定时区,并且驱动类包名发生了变化。
package com.atguigu.entities;
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "name")
private String name;
//此处省略setter和getter方法... ...
}
package com.atguigu.dao;
import com.atguigu.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository<User, Long> {
}
package com.atguigu.service;
import com.atguigu.entities.User;
import java.util.List;
public interface UserService {
List<User> findAll();
User getUserById(Long id);
void saveUser(User user);
void updateUser(User user);
void delete(Long id);
}
package com.atguigu.service.impl;
import com.atguigu.dao.UserDao;
import com.atguigu.entities.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User getUserById(Long id) {
return userDao.getOne(id);
}
@Override
public void saveUser(User user) {
userDao.save(user);
}
@Override
public void updateUser(User user) {
userDao.save(user);
}
@Override
public void delete(Long id) {
userDao.deleteById(id);
}
}
package com.atguigu.controller;
import com.atguigu.entities.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public List<User> findAll(){
List<User> all = userService.findAll();
return all;
}
}
测试运行,控制台打印信息
自动生成的表的存储引擎是MyISAM,此引擎不支持事务,需要该为InnoDB,
创建hibernate.properties配置文件添加以下配置
hibernate.dialect.storage_engine=innodb
删除表重写启动服务器
create database springboot character set utf8 ;
use springboot ;
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`gender` varchar(5) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(32) DEFAULT NULL,
`qq` varchar(20) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`username` varchar(20) NOT NULL,
`phone` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_username_uindex` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `tb_user` VALUES (1,'黄蓉','女',38,'桃花岛','212223390222','[email protected]','huangrong','15600003333'),(2,'黄老邪','男',58,'湖北省武汉市','212223390','[email protected]','huanglaoxie','15872320405'),(3,'小龙女','男',18,'湖北省荆门市','212223390','[email protected]','xiaolongnv','15600004444'),(7,'杨过','男',30,'扬州','212223390','[email protected]','yangguo','15600005555');
创建项目 springboot_case
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.2.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
<dependency>
<groupId>tk.mybatisgroupId>
<artifactId>mapper-spring-boot-starterartifactId>
<version>2.1.5version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
package com.atguigu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan(basePackages = "com.atguigu.dao") // 扫描Mapper接口
@EnableTransactionManagement // 开始事务注解支持
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
server:
port: 10001
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql:///springboot?serverTimezone=Asia/Shanghai
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
type-aliases-package: com.atguigu.pojo
package com.atguigu.pojo;
import java.io.Serializable;
@Entity
@Table(name = "tb_user")
public class User implements Serializable {
@Id
private Integer id;
private String name;
private String gender;
private Integer age;
private String address;
private String qq;
private String email;
private String username;
private String phone;
// …省略了getter和setter方法和toString方法
}
package com.atguigu.dao;
import com.atguigu.pojo.User;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface UserMapper extends Mapper<User> {
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper ;
@Test
public void findAll() {
List<User> users = userMapper.selectAll();
System.out.println(users);
}
}
public interface UserService {
/**
* 查询所有用户信息
* @return
*/
public List<User> findAll();
}
package com.atguigu.service.impl;
import com.atguigu.dao.UserMapper;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
@Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
public List<User> findAll() {
return userMapper.selectAll();
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void findAll() {
List<User> users = userService.findAll();
System.out.println(users);
}
}
Spring Boot整合单元测试 , 需要在测试类上添加二个注解
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
dependency>
package com.atguigu.utils;
import java.io.Serializable;
public class Result implements Serializable {
private boolean status ; //响应状态 true false
private String msg ; // 响应信息
private Object data ; //处理成功的响应数据
public static Result ok(Object data){
Result result = new Result();
result.setStatus(true);
result.setData(data);
return result ;
}
public static Result error(String msg){
Result result = new Result();
result.setStatus(false);
result.setMsg(msg);
return result ;
}
// 生成set get tostring方法
}
@Controller
@RequestMapping(path = "/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 查询所有用户信息
* @return
*/
@RequestMapping(path = "/findAll")
@ResponseBody
public Result findAll() {
List<User> users = userService.findAll();
return Result.ok(users);
}
}
在resources目录下创建static目录 , 将提供的页面复制进来 , 修改即可 :
• 页面异步请求的端口和服务器端口一致
• 页面异步请求访问的路径和对应的表现层控制方法路径要致
• 页面异步请求参数名称和和对应的表现层控制方法参数一致
修改之后, 访问页面即可 : localhost:10001/list.html
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
spring:
redis: # 配置redis
host: 192.168.6.100
port: 6379
package com.atguigu.service.impl;
import com.atguigu.mapper.UserMapper;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper ;
@Autowired
private RedisTemplate redisTemplate ;
@Override
@Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
public List<User> findAll() {
//从缓存中查询数据 规定存储用户信息使用string类型进行存储, 存储的key就是userList
List<User> userList = (List<User>) redisTemplate.boundValueOps("userList").get();
//如果缓存中没有数据, 查询数据库 , 将查询到的数据放入缓存
if(userList==null){
userList = userMapper.findAll();
redisTemplate.boundValueOps("userList").set(userList);
System.out.println("从数据库中查询...");
}else {
System.out.println("从缓存中查询.....");
}
//如果缓存中有数据, 直接返回
return userList ;
}
}
在pom.xml中配置Spring Boot项目的maven插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
打包之前我们需要跳过测试 , 如果不跳过测试那么我们编写的测试类都会被maven自动执行, 可能会出现错误,导致打包不成功
打开指定目录就可以发现有一个jar包存在 。
仔细观察其实我们会发现 , 在target目录下其实会存在二个jar包 ,
那么这两个jar包有什么区别呢?
我们如果是普通项目打包那么就只会得到一个jar包 , 这个jar包中不包含项目的一些依赖jar包
但是我们现在是一个Spring Boot项目 , 我们希望打完的包能够直接运行, 所以项目中就必须包含他的依赖jar包 , 我们之前在pom.xml中配置一个Spring Boot的maven插件可以在普通包的基础上将我们项目的一些运行及依赖信息打进jar包里面 , 打完包之后将原来的普通包改名为xxx.jar.original , 新打的包为xxx.jar .
.jar.original 是普通jar包,不包含依赖
.jar 是可执行jar包,包含了pom中的所有依赖,可以直接用java -jar 命令执行
如果是部署,就用.jar , 如果是给别的项目用,就要给.jar.original这个包
打开命令行运行打出来的包;使用命令:java –jar 包全名
java -jar springboot_02-1.0-SNAPSHOT.jar