SpringBoot快速创建方法
使用idea创建
1.创建新模块使用spring Initializr,并配置基础信息
2.选择技术集
3.开发控制器类
4.运行生成的Application类
SpringBoot官网创建
1.打开springboot官网创建工程
2.保存
3.导入idea中
SpringBoot阿里云在idea创建
-
选择start自定义url
-
创建新模块使用spring Initializr,并配置基础信息
-
选择技术集
-
开发控制器类
-
运行生成的Application类
SpringBoot三种配置方式
application.properties(传统格式)
application.yml (主流格式 推荐使用)
application.yaml
三种配置方式的优先级
application.properties>application.yml >application.yaml
三种配置同时存在时
不同配置文件中相同配置按优先级覆盖,不同配置全部保留。
(共存叠加,相互覆盖)
yml格式属性名冒号后面与数据有一个空格
yaml数据读取
使用@Value读取单个数据,数据名$(一级属性名.二级属性名)
1.使用@Value读取单个数据名
2.多层级,依次书写层级名称
例如:
@Value("${like}") private String like1; @Value("${user[2]}") private String name1; @Value("${user2[1].name}") private String name2;
yml配置文件内部引用
使用${}
\t \n 连接起来是转义字符,如果要想生效使用双引号包裹,不使用双引号则按原字符打印。
使用自动装配将所有数据封装到Environment对象中
例如:
@Autowired
private Environment env;
获取值
env.getProperty("like")
env.getProperty("user2[1].name")
@Autowired:自动装配
使用自定义对象封装指定数据
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/数据库?serverTimezone=UTC
username: root
password: root
@Component
@ConfigurationProperties(prefix = "datasource")
public class DataSource {
private String drivar;
private String url;
private String username;
private String password;
}
小结:
使用@ConfigurationProperties注解绑定配置信息到封装类
封装类要Spring管理Bean,否则无法属性注入
整合Junit
@SpringBootTest 设置Junit加载springBoot启动类
1.导入starter依赖
2.测试类使用@SpringBootTest 修饰
3.自动装配添加对象
整合Mybatis
1.创建新模块,配置模块相关信息
2.选择当前模块技术集
3.设置数据源参数
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/user?serverTimezone=UTC
username: root
password: 123456
4.定义数据接口和映射配置
@Mapper
public interface DepaDao {
@Select("select * from depa where did = #{id}")
public Depa getById(Integer id);
}
5.测试
@SpringBootTest
class Springboot05MybatisApplicationTests {
@Autowired
private DepaDao depaDao;
@Test
void contextLoads() {
System.out.println(depaDao.getById(1));
}
}
数据sql映射需要添加@Mapper被容器识别到
整合MyBatis Plus
1.手动添加mybati plus坐标
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
2.数据层接口与映射配置继承BeseMapper
@Mapper
public interface DepaDao extends BaseMapper<Depa> {
}
整合Druid
1.导入Druid对应的starter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
2.变更Druid的配置方式
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/数据库名?serverTimezone=UTC
username: 账号
password: 密码