SpringBoot从入门到使用

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)

配置文件

  1. application.properties
    server.port=9876
    spring.datasource.username=root
    spring.datasource.password=111111
    
  2. 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包含:

  1. @SpringBootConfiguration
    SpringBoot Bean定义,SpringBoot通过@Bean、@Primary标记定义。

  2. @ComponentScan
    SpringBoot组件扫描

  3. @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数据

  1. 导jat包,通常使用maven。
  2. 启动类
  3. 配置文件 >> 端口号
  4. Controller类
    返回 json 类型得数据需要 @ResponseBody 注解。使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中。
@Controller
public class HelloController {

	@RequestMapping("/hello")
	@ResponseBody
	public String say() {
		return "hello springboot";
	}
}

2.2 数据库访问

  1. 导jar包,jdbc,mysql驱动包
  2. 启动类
  3. 配置文件
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/xxx
spring.datasource.driverClassName=com.mysql.jdbc.Driver
  1. 启动类(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访问数据库

  1. 导jar包 spring-boot-starter-jdbc后(hikari、spring-jdbc包)、驱动包,创建连接池。
  2. 配置文件
  3. 根据要操作表定义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;
    }
		
}
  1. 定义Dao接口
public interface DirectionDao {	
	public List<Direction> findAll();
}
  1. 定义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);
    }
		
}
  1. 启动类
@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版本)

  1. 导jar包 spring-boot-starter-jdbc、驱动包、mybatis-spring-boot-starter
  2. 配置文件
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
  1. 实体类
  2. Mapper接口
public interface DirectionMapper {
    public List<Direction> selectAll();
    public Direction selectById(int id);
}
  1. 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>
  1. 启动类
@SpringBootApplication
@MapperScan(basePackages="cn.hh.dao")//扫描Mapper接口创建对象加载到Spring容器
public class RunBoot {
		... ...
}

3.SpringBoot MVC

3.1 SpringBoot MVC开发JSP应用

  1. 导jar包 导入spring-boot-starter-web、jasper解析器、jstl
  2. 配置文件 > 端口号
server.port=8888
#/src/main/webapp/xxx.jsp
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
  1. 启动类
  2. 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;
	}

}
  1. 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

  1. 导jar包 spring-boot-starter-web、spring-boot-starter-thymeleaf
  2. 配置文件
  3. 启动类
  4. 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 + "成功";
    }
}

  1. 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值