昨天给大家介绍了SpringBoot官方文档的入门案例,相信大家现在已经可以使用SpringBoot开发一些简单的小demo了,那么今天我们就来学习一下SpringBoot的一些常用的配置,首先我们先来创建一个项目,项目结构如下:
关于这几个目录先给大家介绍下 ,首先大家肯定知道我们编写的代码都是在src/main/java路径下,test包下是存放测试的代码,那么毫无疑问resources目录下 存放的肯定就是项目需要用到的一些配置文件,我们发现其中有一个application文件,好吧,这个就是SpringBoot的核心配置文件,我们可以通过这个文件修改SpringpBoot的一些默认的配置信息。static文件夹是用来存放静态文件的,例如css文件,js文件 等等 ,最后templates文件存放就是模板,比如我们熟悉的jsp以及thymeleaf等模板。好了,接下来我们来引入一个简单的页面来学习一下。
首先我们在pom文件中加入thymeleaf 的依赖 ,一来可以根据官方文档提供的方式找或者直接去maven中央仓库找,如下所示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
接着我们在resources/templates目录下创建一个html文件,并且在html标签中导入thymeleaf的名称空间。如下所示
接着我们在BestPracticesApplication中编写一个方法,返回一个视图,代码如下:
@RequestMapping("/")
public String bestPractices(ModelMap map) {
map.addAttribute("message", "SpringBoot2.4 的页面");
return "bestPractices";
}
好了,接下来我们使用thymeleaf的标签取出message 这个值 并且显示在页面上,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>thymeleaf模板 </h1>
<h1 th:text="${message}">Hello World</h1>
</body>
</html>
最后我们启动一下项目,在浏览器访问就可以看到效果了
到了这里大家可能会有疑惑,SpringBoot是怎么找到bestpractices.html这个文件的,上篇博客中给大家介绍了@EnableAutoConfiguration这个注解的作用,我们都知道这个注解就是告诉SpringBoot做一些默认的配置,好吧机智的你一定发现了这个项目里面压根就没有用到@EnableAutoConfiguration这个注解啊。我们回到BestPracticesApplication这个类中,我们发现有一个SpringBootApplication这个注解,好吧 我们点击去看,发现这是一个复合注解,源码信息如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "nameGenerator")
Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
@AliasFor(annotation = Configuration.class)
boolean proxyBeanMethods() default true;
}
好吧,我们在这个注解的源码中发现这个注解其实已经包含了@EnableAutoConfiguration这个注解了,好吧 那我们就可以暂时的先认为SpringBootApplication这个注解也可以告诉SpringBoot做一些默认的配置。同样的我们点击去看看@EnableAutoConfiguration这个注解的源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
/**
* Environment property that can be used to override when auto-configuration is
* enabled.
*/
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
}
我们似乎看不出来这里具体的逻辑,但是我们发现这个注解的源码中还使用了@AutoConfigurationPackage ,好吧,我们继续点进去看看这个注解会发现这个注解是初始化当前包下的资源,好吧 我们看看这个包下都有一些什么:
图只截出来了一部分,我们继续往下看,会发现有一个thymeleaf 的包,我们可以点开看看这个包里面有些什么内容:
我们可以看到 ThymeleafProperties 这个类中定义了 DEFAULT_PREFIX和DEFAULT_SUFFIX这两个静态常量,并且我们可以看到他们的默认值,好吧,到了这里大家应该就知道了SpringBoot是怎么找到bestPractices.html这个页面的吧。到这里我们再开发的时候就可以将一些常规的静态模板文件放在templates目录下了。
好了,关于thymeleaf具体的语法这里就不做过多的讨论,大家可以自行去官网了解,我们把重点放在SpringBoot上。下面就来学习一下SpringBoot的核心配置文件。首先我们来到官方提供的文档上https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties如下图所示:
关于怎么编写核心配置文件,这个章节就是提供给我们的参考,这里先给大家介绍几个比较常见的配置 ,比如我们想修改tomcat的端口,假如我们像使用9000端口 那么我们就可以参照 Server Properties这个章节的配置,如下图所示:
其中的server.port 这个配置的值就是对应端口值 SpringBoot 默认设置的是8080。我们在程序中的核心配置文件加上server.port = 9000,然后重新启动形目就会发现端口已经改成了9000了。
好了这个相信大家都会了,我们在撸项目的时候一定会操作数据,那么下面我们就来学习一下怎么配置数据库,大家找到下图所示的位置
我们在配置文件中加入以下内容
#端口
server.port=9000
#mysql配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/optimum?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
#thymeleaf缓存配置
spring.thymeleaf.cache=false
#整合MyBatis
mybatis.mapper-locations=classpath:mapper/*.xml
接着我们在resources 目录下创建一个mapper文件夹,这里的resources目录就是我们常说的classpath,项目编译的时候这个目录的内容就会被编译到项目的classpath路径下
接下来就是我们熟悉的Spring整合Mybatis的流程了,编写接口和xml文件,不过我们需要事先准备一张简单的表,这里我的表结构如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`hobby` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.wcan.boot.mapper.UserMapper">
<resultMap id="BaseResultMap" type="org.wcan.boot.bean.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="hobby" jdbcType="VARCHAR" property="hobby" />
</resultMap>
<sql id="Base_Column_List">
id,name,age,email,hobby
</sql>
<select id="selectUserList" resultMap="BaseResultMap">
select <include refid="Base_Column_List" />
from user
</select>
</mapper>
对应的代码如下:
public interface UserMapper {
public List<User> selectUserList();
}
public interface UserService {
public List<User> selectUserList();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectUserList() {
return userMapper.selectUserList();
}
}
@Controller
public class BestPracticesController {
@Autowired
private UserService userService;
@RequestMapping("/")
public String bestPractices(ModelMap map) {
List<User> users = userService.selectUserList();
users.forEach(user -> System.out.println(user));
map.addAttribute("list",users);
map.addAttribute("message", "SpringBoot2.4 的页面开发");
return "bestPractices";
}
}
ublic class User {
private Integer id;
private String name;
private Integer age;
private String email;
private String hobby;
//get set。。。。。
}
最后有一个简单的页面,页面的内容如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>thymeleaf模板 </h1>
<h1 th:text="${message}">Hello World</h1>
<h1>th:each 循环遍历 List 集合</h1>
<div style="color: red" th:each="user,userStat:${list}">
<span th:text="${userStat.index}"></span>
<span th:text="${user.id}"></span>
<span th:text="${user.name}"></span>
<span th:text="${user.age}"></span>
<span th:text="${user.email}"></span>
<span th:text="${user.hobby}"></span>
</div>
</body>
</html>
好了,我们启动项目之后就可以看到效果了,这就是一个简单的查询的功能,感兴趣的小伙伴可以尝试者完成增删改查。