springboot学习笔记 -- 基于spring5、springboot2.0的应用

一、Spring Boot介绍


1、什么是springboot


        Srping Boot 是由Pirvotal团队提供的全新框架,其设计目的是用来简化新spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不需要定义样板化的配置。


2、springboot特性


(1)、创建独立的spring应用程序


(2)、嵌入的Tomcat,无需部署WAR文件


(3)、简化Maven配置


(4)、自动配置spring


(5)、提供生产就绪型功能,如:指标、健康检查和外部配置


(6)、开箱即用,没有代码生成,也无需XML配置


3、spring boot特性理解


(1)、为基于Spring的开发提供更快的入门体验


(2)、开箱即用,没有代码生成,也无需XML配置,同时也可以修改默认值来满足特定的需求


(3)、提供了一些大型项目中常见的非功能特性,如嵌入式服务、安全、指标、健康检查、外部配置等。


(4)、Spring Boot 并不是对spring功能上的增强,而是提供了一种快速使用spring的方式


二、Spring Boot之入门案例


说明:本章所用到的资料下载路径:https://download.csdn.net/download/wingzhezhe/10521675


1、创建maven project,打包方式为jar




2、pom.xml中引入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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<groupId>com.springboot</groupId>
	<artifactId>springboot_demo1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- 加入web工程必须要的依赖,会直接依赖很多启动web工程需要的包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
</project>


3、编写启动引导类




package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * springboot启动引导类
 * 
 * @author wingz
 *
 */

@SpringBootApplication // springboot引导类标识符
public class Starter {

	public static void main(String[] args) {
		// 引导启动方法,参数1为引导类(带有@SpringBootApplication注解的类)
		SpringApplication.run(Starter.class, args);
	}
}


4、编写控制层代码


package com.springboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * springboot的控制层 
 * 
 * 注意:控制层代码必须卸载启动引导类的同级或者子目录中才能够生效
 * 
 * @author wingz
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@RequestMapping("showUser")
	public String showUser() {
		return "{name:'小明', age:17}";
	}
}


三、springboot基于spring5、springboot2.0版本的的热部署


1、特殊说明


        在 spring5.x 时,必须使用 springloaded 最新版 1.2.9。因为 spring5.x 采用的是 1.8 为内核编写的。而springloaded1.2.9 以前的版本都不支持 spring5.x。


2、使用命令将springloaded-1.2.9.BUILD.jar安装到本地仓库


mvn install:install-file -DgroupId=org.springframework -DartifactId=springloaded -Dversion=1.2.9 -Dpackaging=jar -Dfile=springloaded-1.2.9.BUILD.jar




注意:使用命令将jar包安装到本地仓库中时,需要配置maven的环境变量,且对应的仓库必须是当前要安装到的Maven仓库


3、pom.xml中加入2.0版本的热部署插件




4、在Eclipse中配置启动参数




-javaagent:E:\project_reponsitory\study\maven_repository\org\springframework\springloaded\1.2.9\springloaded-1.2.9.jar -noverify




修改完参数点击run即可,启动之后便已经完成热部署配置


四、springboot整合spring-data-jpa的使用


1、搭建环境


(1)、导入数据库表


DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_name` varchar(100) DEFAULT NULL COMMENT '用户名',
`password` varchar(100) DEFAULT NULL COMMENT '密码',
`name` varchar(100) DEFAULT NULL COMMENT '姓名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'zhangsan', '123456', '张三');
INSERT INTO `user` VALUES ('2', 'lisi', '123456', '李四');
INSERT INTO `user` VALUES ('3', 'wangwu', '123456', '王五');
INSERT INTO `user` VALUES ('4', 'zhangwei', '123456', '张伟');
INSERT INTO `user` VALUES ('5', 'lina', '123456', '李娜');
INSERT INTO `user` VALUES ('6', 'lilei', '123456', '李磊');


(2)、创建Maven Project的springboot工程




(3)、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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<groupId>com.springboot</groupId>
	<artifactId>springboot_dataJPA</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<!-- web工程所需依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 热部署插件依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
			<version>1.2.9</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<!-- spring-data-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>
		</dependency>
	</dependencies>
</project>


(4)、编写引导类




package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * 该类就是运行器,它会自动扫描当前包下的spring bean对象以及子包下的bean对象
 * 		spring bean对象是指被注解修饰过的类:@Controller @Service @Respository @Component  @RestController
 * @author wingz
 *
 */
@SpringBootApplication
public class SpringBootApplicationRunner {
	
	/**
	 * 启动方法
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(SpringBootApplicationRunner.class, args);
	}

}


2、后台代码编写




(1)、用户实体类


package com.springboot.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 用户实体类
 * 
 * @author wingz
 *
 */
@Entity
@Table(name = "user")
public class User implements Serializable {

	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	@Column(name = "user_name")
	private String username;

	@Column(name = "password")
	private String password;

	@Column(name = "name")
	private String name;

	getter/setter

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", name=" + name + "]";
	}

}


(2)、IUserDao.java


package com.springboot.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.springboot.domain.User;

/**
 * 持久层接口
 * 
 * @author wingz
 *
 */
public interface IUserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {

}


(3)、service层接口和实现类


package com.springboot.service;

import java.util.List;

import com.springboot.domain.User;

/**
 * 业务层接口
 * 
 * @author wingz
 *
 */
public interface IUserService {

	/**
	 * 查询所有用户
	 * 
	 * @return
	 */
	List<User> findAll();

	/**
	 * 根据id查询用户
	 * 
	 * @param id
	 * @return
	 */
	User findById(Integer id);
}


package com.springboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.springboot.dao.IUserDao;
import com.springboot.domain.User;
import com.springboot.service.IUserService;

/**
 * 业务层实现类
 * 
 * @author wingz
 *
 */
@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	public User findById(Integer id) {
		return userDao.findById(id).get();
	}
}


(4)、web层


package com.springboot.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.domain.User;
import com.springboot.service.IUserService;

/**
 * web层
 * 
 * @author wingz
 *
 */
@RestController
@RequestMapping("user")
public class UserController {

	@Autowired
	private IUserService userService;

	/**
	 * 查询所有用户
	 * 
	 * @return
	 */
	@RequestMapping("findAll")
	public List<User> findAll() {
		return userService.findAll();
	}

	/**
	 * 根据id查询
	 * 
	 * @return
	 */
	@RequestMapping("findById/{id}")
	public User findById(@PathVariable("id") Integer id) {
		return userService.findById(id);
	}
}


3、前端页面编写


注意:springboot中的页面必须为html页面,必须放在src/main/resource下的static文件夹中(需要自己创建static文件夹),此static文件名称不能变,该文件相当于web工程中的webapps




4、加入springboot配置文件application.properties




#DB Configuration:数据库配置信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot
spring.datasource.username=root
spring.datasource.password=1234

#JPA Configuration:JPA详细配置(数据库方言、是否显示sql等)
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy


5、访问测试




五、springboot整合MyBatis


1、环境搭建


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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<groupId>com.springboot</groupId>
	<artifactId>sprinboot_mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
			<version>1.2.9</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
	</dependencies>
</project>


其他环境同整合spring-data-jpa


2、后台代码


(1)、实体类


package com.springboot.domain;

import java.io.Serializable;

/**
 * 用户实体类
 * 
 * @author wingz
 *
 */
public class User implements Serializable {

	private Integer id;
	private String username;
	private String password;
	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer 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 getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", name=" + name + "]";
	}

}


(2)、持久层接口


package com.springboot.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.springboot.domain.User;

/**
 * 持久层接口
 * 
 * @author wingz
 *
 */
@Mapper // 需要此处加入一个新的注解,表明它是个mybatis的映射类
public interface IUserDao {

	/**
	 * 查询所有
	 * 
	 * @return
	 */
	@Select("select * from user")
	@Results(id = "userMap", value = { 
				@Result(id = true, column = "id", property = "id"),
				@Result(column = "user_name", property = "username"), 
				@Result(column = "password", property = "password"),
				@Result(column = "name", property = "name"), })
	List<User> findAll();

	/**
	 * 使用名称模糊查询
	 * 
	 * @param username
	 * @return
	 */
	@Select("select * from user where user_name like #{username}")
	@ResultMap("userMap")
	List<User> findUserByName(String username);

}


(3)、业务层接口及实现类


package com.springboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springboot.dao.IUserDao;
import com.springboot.domain.User;
import com.springboot.service.IUserService;

/**
 * 业务层实现类
 * 
 * @author wingz
 *
 */
@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	/**
	 * 模糊查询
	 */
	public List<User> findUserByName(String username) {
		return userDao.findUserByName(username);
	}

}


(4)、web层代码


package com.springboot.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.domain.User;
import com.springboot.service.IUserService;

/**
 * 控制层
 * 
 * @author wingz
 *
 */
@RestController
@RequestMapping("user")
public class UserController {

	@Autowired
	private IUserService userService;

	/**
	 * 查询所有用户
	 * 
	 * @return
	 */
	@RequestMapping("findAll")
	public List<User> findAll() {
		return userService.findAll();
	}

	/**
	 * 根据名称模糊查询用户
	 * 
	 * @return
	 */
	@RequestMapping("findUserByName")
	public List<User> findUserByName() {
		return userService.findUserByName("%i%");
	}
}


3、springboot配置文件


#DB Configuration:数据库配置信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot
spring.datasource.username=root
spring.datasource.password=admin123


六、springboot整合redis


1、创建maven project 


项目创建同data-jpa


2、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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<groupId>com.springboot</groupId>
	<artifactId>springboot_redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
			<version>1.2.9</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
			<version>1.4.4.RELEASE</version>
		</dependency>
	</dependencies>
</project>


3、主配置文件application.properties


#DB Configuration:数据库配置信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot
spring.datasource.username=root
spring.datasource.password=admin123

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.25.128
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=50000


4、启动引导类


package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * 该类就是运行器,它会自动扫描当前包下的spring bean对象以及子包下的bean对象
 * 		spring bean对象是指被注解修饰过的类:
 * 				@Controller @Service @Respository @Component  @RestController
 * @author wingz
 *
 */
@SpringBootApplication
@EnableCaching	//该注解用于开启springboot中对缓存的支持
public class SpringBootApplicationRunner {
	
	/**
	 * 启动方法
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(SpringBootApplicationRunner.class, args);
	}

}


5、IUserDao.java


package com.springboot.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.springboot.domain.User;

/**
 * 持久层接口
 * 
 * @author wingz
 *
 */
@Mapper // 需要此处加入一个新的注解,表明它是个mybatis的映射类
public interface IUserDao {

	/**
	 * 查询所有
	 * 
	 * @return
	 */
	@Select("select * from user")
	@Results(id = "userMap", value = { 
				@Result(id = true, column = "id", property = "id"),
				@Result(column = "user_name", property = "username"), 
				@Result(column = "password", property = "password"),
				@Result(column = "name", property = "name"), })
	List<User> findAll();

	/**
	 * 使用名称模糊查询
	 * 
	 * @param username
	 * @return
	 */
	@Select("select * from user where user_name like #{username}")
	@ResultMap("userMap")
	List<User> findUserByName(String username);

}


6、UserServiceImpl.java


package com.springboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.springboot.dao.IUserDao;
import com.springboot.domain.User;
import com.springboot.service.IUserService;

/**
 * 业务层实现类
 * 
 * @author wingz
 *
 */
@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;

	// 该注解作用是将查询的结果放入redis中,并且redis中数据对应的key为all_list
	@Cacheable("all_list")
	public List<User> findAll() {
		return userDao.findAll();
	}

	/**
	 * 模糊查询
	 */
	// 该注解作用是调用方法时,清除对应key值的缓存,key的值为all_list
	// allEntries:是否清除value对应的所有缓存,默认值为false
	@CacheEvict(value = "all_list", allEntries = true)
	public List<User> findUserByName(String username) {
		return userDao.findUserByName(username);
	}

}


7、UserController.java


package com.springboot.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.domain.User;
import com.springboot.service.IUserService;

/**
 * 控制层
 * 
 * @author wingz
 *
 */
@RestController
@RequestMapping("user")
public class UserController {

	@Autowired
	private IUserService userService;

	/**
	 * 查询所有用户
	 * 
	 * @return
	 */
	@RequestMapping("findAll")
	public List<User> findAll() {
		return userService.findAll();
	}

	/**
	 * 根据名称模糊查询用户
	 * 
	 * @return
	 */
	@RequestMapping("findUserByName")
	public List<User> findUserByName() {
		return userService.findUserByName("%i%");
	}
}


七、springboot整合junit


1、环境同上,只有junit测试类不一样,如下


package com.test;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.springboot.SpringBootApplicationRunner;
import com.springboot.domain.User;
import com.springboot.service.IUserService;

@RunWith(SpringJUnit4ClassRunner.class)
// 改注解是springboot整合junit中用来获取引导类的注解
@SpringBootTest(classes = SpringBootApplicationRunner.class)
public class SpringBootJunitTestDemo {

	@Autowired
	private IUserService userService;

	@Test
	public void testFindAll() {
		List<User> findAll = userService.findAll();
		System.out.println(findAll);
	}

}


八、springboot读取配置文件


说明:配置文件都需要放在src/main/resources根路径下


1、读取常用的application.properties配置文件的方式


(1)、application.properties


#配置端口号
server.port=8585

#数据库的连接配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ee39_springboot
spring.datasource.username=root
spring.datasource.password=1234


(2)、SpringBootJunitTestDemo.java


package com.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.springboot.SpringBootApplicationRunner;

@RunWith(SpringJUnit4ClassRunner.class)
// 改注解是springboot整合junit中用来获取引导类的注解
@SpringBootTest(classes = SpringBootApplicationRunner.class)
public class SpringBootJunitTestDemo {

	@Autowired
	private Environment evm;

	/**
	 * 读取SpringBoot的核心配置文件
	 * 
	 * spring boot的核心配置文件是application.properties的文件
	 * 里面写的就是key=value的内容
	 * 
	 * 配置启动时服务器的端口号:
	 * 		server.port=8585
	 */
	@Test
	public void testReadCoreConfig() {
		//1.获取连接数据库的用户名
		String username = evm.getProperty("spring.datasource.username");
		System.out.println(username);
	}

}


2、读取自定义配置文件


(1)、自定义配置文件:mail.properties


mail.host=smtp.sina.com 
mail.port=25 
mail.username=itcast 
mail.password=heima


(2)、创建用于封装配置文件中数据的实体类对象


package com.springboot.domain;

import java.io.Serializable;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
 * 
 * 用于封装邮件信息的实体类
 */
@Configuration
@PropertySource("classpath:mail.properties")
@ConfigurationProperties(prefix="mail",ignoreUnknownFields=false) //prefix用于指定配置文件中对应的key的前缀
public class Mail implements Serializable {

	private String host;
	private String port;
	private String username;
	private String password;
	
	getters/setters
	@Override
	public String toString() {
		return "Mail [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password + "]";
	}
	
	
}


(3)、测试类读取配置文件内容


package com.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.springboot.SpringBootApplicationRunner;
import com.springboot.domain.Mail;

@RunWith(SpringJUnit4ClassRunner.class)
// 改注解是springboot整合junit中用来获取引导类的注解
@SpringBootTest(classes = SpringBootApplicationRunner.class)
public class SpringBootJunitTestDemo {

	/**
	 * 读取自定义配置文件,只需要使用三个注解
	 */
	@Autowired
	private Mail mail;
	
	@Test
	public void testReadCustomConfig() {
		System.out.println(mail);
	}

}


3、读取yml格式的配置文件:application.yml


(1)、yml语法格式


普通数据:
	key:value
	在 key 和 value 中必须有一个空格

对象数据:
	mail:
	host: smtp.sina.com
	port: 25
	username: itcast
	password: heima


(2)、application.yml配置文件


#yml的语法:要求key后面是:,冒号后面必须有一个空格,然后再跟值

mail: 
  host: stmp.sina.com
  port: 25
  username: itcast 
  password: 1234


(3)、创建读取yml配置文件的实体类


package com.itheima.domain;

import java.io.Serializable;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 
 * 读取yml配置文件
 */
@Configuration
@ConfigurationProperties(prefix="mail")
public class MailYml implements Serializable {

	private String host;
	private String port;
	private String username;
	private String password;
	
	setter/getter
	
	@Override
	public String toString() {
		return "Mail [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password + "]";
	}
	
	
}


(4)、junit测试文件读取application.yml


package com.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.springboot.SpringBootApplicationRunner;
import com.springboot.domain.MailYml;

@RunWith(SpringJUnit4ClassRunner.class)
// 改注解是springboot整合junit中用来获取引导类的注解
@SpringBootTest(classes = SpringBootApplicationRunner.class)
public class SpringBootJunitTestDemo {

	/**
	 * 读取yml配置文件
	 */
	@Autowired
	private MailYml mailYml;
	
	
	/**
	 * Value注解它适合获取单个的数据
	 */
	@Value("${mail.host}")
	private String host;
	
	@Value("${spring.datasource.driverClassName}")
	private String driverClass;
	
	@Test
	public void testReadYml() {
		System.out.println(mailYml);
		
		System.out.println(host);
		System.out.println(driverClass);
	}

}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值