1.简介
SpringBoot是对Spring框架得封装,用于简化Spring应用得开发。编码简单、配置简单、部署简单、监控简单。
构成:(主要包)
- spring-boot-starter(核心、ioc、yml、自动配置、日志)
- spring-boot-starter-parent(参数设置、文件编码、jdk版本)
- spring-boot-starter-jdbc(连接池、jdbcTemplate)
- spring-boot-starter-web(mvc、restful、tomcat)
- spring-boot-starter-test(junit、spring-test)
配置文件
- application.properties
server.port=9876 spring.datasource.username=root spring.datasource.password=111111
- application.yml
spring:
datasource:
username: root
password: 111111
server:
port: 9876
启动
springboot内置了tomcat,需要写一个启动类,注解不能少。
@SpringBootApplication
public class xxx{
public static void main(String[] args){
SpringApplication.run(xxx.class,args);
}
}
注解
@SpringBootApplication包含:
@SpringBootConfiguration
SpringBoot Bean定义,SpringBoot通过@Bean、@Primary标记定义。@ComponentScan
SpringBoot组件扫描@EnableAutoConfiguration
自动配置机制是SpringBoot框架特有功能,能在启动后自动创建一些常用对象,例如DataSource、JdbcTemplate等。
- 自动配置原理
在xxx-autoconfigure.jar包中META-INF目录下有一个spring.factories文件,其中定义了大量的xxxAutoConfiguration配置组件。
当开启@EnableAutoConfiguration标记时,标记内部会触发AutoConfigurationImportSelector组件调用SpringFactoriesLoader加载spring.factories文件。
自动配置组件就是采用@Configuration+@Bean+@Primary标记事先定义好的配置组件,通过Boot启动自动去spring.factories文件加载,然后在Spring容器中创建出约定对象。
2.案例
2.1 返回JSON数据
- 导jat包,通常使用maven。
- 启动类
- 配置文件 >> 端口号
- Controller类
返回 json 类型得数据需要 @ResponseBody 注解。使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中。
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String say() {
return "hello springboot";
}
}
2.2 数据库访问
- 导jar包,jdbc,mysql驱动包
- 启动类
- 配置文件
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/xxx
spring.datasource.driverClassName=com.mysql.jdbc.Driver
- 启动类(DataSource和JdbcTemplate都是基于自动配置机制产生,直接注入使用即可)
@SpringBootApplication
public class RunBoot {
public static void main(String[] args) throws SQLException {
ApplicationContext ctx = SpringApplication.run(RunBoot.class, args);
DataSource ds = ctx.getBean(DataSource.class);
System.out.println(ds.getConnection());
JdbcTemplate template = ctx.getBean(JdbcTemplate.class);
System.out.println(template);
String sql = "insert into paper_score (total_score,my_score,user_id) values (?,?,?)";
Object[] params = {100,90,1};
template.update(sql,params);
}
}
2.3 Spring DAO JdbcTemplate访问数据库
- 导jar包 spring-boot-starter-jdbc后(hikari、spring-jdbc包)、驱动包,创建连接池。
- 配置文件
- 根据要操作表定义entity
public class Direction {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 定义Dao接口
public interface DirectionDao {
public List<Direction> findAll();
}
- 定义Dao实现类,扫描并注入JdbcTemplate使用
@Repository//通过组件扫描加载到Spring容器
public class JdbcDirectionDao implements DirectionDao {
@Autowired
private JdbcTemplate template;//通过自动配置加载到Spring容器
@Override
public List<Direction> findAll() {
String sql = "select * from direction";
RowMapper<Direction> rowMapper =
new BeanPropertyRowMapper<Direction>(Direction.class);
return template.query(sql, rowMapper);
}
}
- 启动类
@SpringBootApplication//开启Bean定义、组件扫描、自动配置机制
public class RunBoot {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(RunBoot.class, args);
DataSource ds = ctx.getBean("dataSource",DataSource.class);
System.out.println(ds);
JdbcTemplate template =
ctx.getBean("jdbcTemplate",JdbcTemplate.class);
System.out.println(template);
DirectionDao dao = ctx.getBean(DirectionDao.class);
List<Direction> list = dao.findAll();
//lambda
list.forEach(d->{System.out.println(d.getId()+" "+d.getName());});
}
}
2.4 MyBatis(XML SQL版本)
- 导jar包 spring-boot-starter-jdbc、驱动包、mybatis-spring-boot-starter
- 配置文件
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/xxx
spring.datasource.driverClassName=com.mysql.jdbc.Driver
mybatis.mapperLocations=classpath:sql/*.xml
- 实体类
- Mapper接口
public interface DirectionMapper {
public List<Direction> selectAll();
public Direction selectById(int id);
}
- mapper.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="cn.hh.dao.DirectionMapper">
<select id="selectAll" resultType="cn.hh.entity.Direction">
select * from direction
</select>
<select id="selectById" parameterType="int" resultType="cn.hh.entity.Direction">
select * from direction where id=#{id}
</select>
</mapper>
- 启动类
@SpringBootApplication
@MapperScan(basePackages="cn.hh.dao")//扫描Mapper接口创建对象加载到Spring容器
public class RunBoot {
... ...
}
3.SpringBoot MVC
3.1 SpringBoot MVC开发JSP应用
- 导jar包 导入spring-boot-starter-web、jasper解析器、jstl
- 配置文件 > 端口号
server.port=8888
#/src/main/webapp/xxx.jsp
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
- 启动类
- Controller
@Controller
public class HelloController {
@RequestMapping("/hello")
public ModelAndView say() {
ModelAndView mav = new ModelAndView();
mav.setViewName("hello");//写视图组件名称
mav.getModel().put("msg", "JSP应用案例");//JSP中${msg}
List<String> list = new ArrayList<>();
list.add("zhangsan");
list.add("lisi");
list.add("wangwu");
mav.getModel().put("list", list);//${list}
return mav;
}
}
- jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello SpringBoot JSP</h1>
<h1>${msg}</h1>
<ul>
<c:forEach items="${list}" var="s">
<li>${s}</li>
</c:forEach>
</ul>
</body>
</html>
3.2 SpringBoot MVC开发Thymeleaf应用
模板使用HTML
- 导jar包 spring-boot-starter-web、spring-boot-starter-thymeleaf
- 配置文件
- 启动类
- Controller
@Controller
@Controller
public class ExcelController {
@GetMapping("/load")
public String toExcel() {
return "load";
}
@RequestMapping("/uploadTest1")
public @ResponseBody
String test1(@RequestParam("imgFile") MultipartFile file) {
//获取上传文件名,包含后缀
String originalFilename = file.getOriginalFilename();
//获取后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//保存路径
//springboot 默认情况下只能加载 resource文件夹下静态资源文件
String path = "C:\\Users\\Administrator\\Desktop\\";
//生成保存文件
File uploadFile = new File(path + originalFilename);
System.out.println(uploadFile);
//将上传文件保存到路径
try {
file.transferTo(uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
return "上传" + originalFilename + "成功";
}
}
- html 放在resources下的templates中 否则模板识别不到
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
<title>Title</title>
</head>
<body>
<form action="uploadTest1" enctype="multipart/form-data" method="post">
<input type="file" name="imgFile"/><br>
<input type="submit" value="上传"/>
</form>
</body>
</html>
版权声明:本文为p1242994784原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。