Springboot
1.1、使用SpringBoot的原因
1、spring和springmvc框架需要大量的配置文件,还需要配置各种对象,把对象放到容器中才能使用
。需要了解其他框架的配置规则
2、springboot相当于不要配置文件的spring和springmvc。常用的框架和第三方库都配置好了。
3、springboot开发效率高。
1.2、JavaConfig
JavaConfig:使用java类作为xml文件的替代,是配置spring容器的纯java代码方式。
使用两个注解:
1、@Configuration:表示这个类是配置文件的作用
2、@Bean:注入到容器中
/**
* 加上@Configuration注解表示这个类是配置文件类,作用类似于xml配置文件
*/
@Configuration
public class MyConfig {
/**
* 创建方法,方法的返回值是对象。在方法上面加上@Bean
* 方法的返回值注入到对象中
* 不指定对象名称,默认是方法名
*/
@Bean("student")
public Student creatStudent(){
Student student =new Student(1,"zs",20);
return student;
}
}
1.2.1、@ImportResource
@ImportResource:作用是导入其他配置文件,等于在xml文件中:
<import resource="其他配置文件"/>
*/
@Configuration
@ImportResource(value = "classpath:application.xml")
public class MyConfig {}
1.2.2 、@PropertyResource
作用:读取property配置文件。
步骤:
- 在resource目录下创建properties配置文件
- 使用@PropertyResource注解指定配置文件位置
- 使用@Value(value="${key}")获取配置文件中的值
@Configuration
@ImportResource(value = "classpath:application.xml")
@PropertySource(value = "classpath:config.properties")
@ComponentScan("com.jfs.pojo")
public class MyConfig {}
@Component("tiger")
public class Tiger {
@Value(value ="${tiger.name}")
private String name;
@Value(value = "${tiger.age}")
private Integer age;
}
1.3、Springboot入门
1.3.1、介绍
springboot是spring的成员,简化了spring和springmvc。它的核心还是ioc容器。
特点:
1、创建spring应用
2、内嵌tomcat等服务器
3、提供了starter起步依赖,简化应用配置。
例如在spring中使用mybatis需要配置sqlssionFactory对象、dao代理对象。
在springboot,在pom文件中加入mybatis-spring-boot-stater依赖就行了。
4、尽可能配置spring和第三方的库。(就是把spring中和第三方库中的对象都创建好,放到容器中,开发人员可以直接使用)
5、提供了健康检查、统计、外部化配置。
6、不用生成代码、xml文件做配置
1.3.2、创建springboot项目
1.3.2.1、第一种方式
通过使用new module----->Spring initializr---------->custom:(https://start.springboot.io)。然后按照步骤进行下去。
1.3.2.2、第二种方式
通过使用new module----->maven------->pom文件导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.3.3、注解的使用
@SpringBootApplication 组成:
1、@SpringBootConfiguration
2、@EnableAutoConfiguration
3、@ComponentScan
@SpringBootConfiguration注解:
是由@Configuration注解组成,所以可以在@SpringBootApplication注解的类中声明对象并注入。
@SpringBootApplication
public class Springboot04MvcApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04MvcApplication.class, args);
}
@Bean
public Student test(){
return new Student();
}
}
@EnableAutoConfiguration
启动自动配置,把java对象配置好,注入到容器中。例如把mybatis对象创建好,注入到容器中。可以把第三方框架的对象创建好,放到容器中。
@ComponentScan
组件扫描器,找到注解,根据注解的功能创建对象,并赋值。默认扫描的包是@SpringBootApplication注解所在的类的包和其子包。
1.3.4、springboot配置文件
配置文件名称:application
扩展名:properties(k=v)、yml(k: v )
1、application.properties配置文件(默认优先使用)
#设置端口号
server.port=9090
#设置应用上下文路径
server.servlet.context-path=/springboot
2、application.yml文件
server:
port: 8082
servlet:
context-path: /springboot2
1.3.5、多环境配置
有开发环境、测试环境、生产环境
名称规则:application-环境名称.properties|yml
application-dev.properties
application-product.properties
application-test .properties
使用方法:
1、新建多个环境的配置文件
2、在application.properties文件中确定使用哪个配置文件,只需要写"-"后面的名称就行了
#使用哪个配置文件
spring.profiles.active=dev
1.3.6、springboot自定义配置
@Value注解:获取配置文件中的值
1、定义配置文件
#定义端口号
server.port=8080
#定义上下文路径
server.servlet.context-path=/my
#自定义key value
my.name=张三
my.age=22
2、获取配置文件中的值
@Controller
public class MyController {
@Value("${my.name}")
private String name;
@Value("${my.age}")
private Integer age;
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "我的名字是:"+name+",我的年纪是:"+age;
}
}
@ConfigurationProperties
作用:在类上面使用,把配置文件的值注入到类中同名的属性中。
@Component
//prefix表示属性前面对应的名称
@ConfigurationProperties(prefix = "my")
public class Person {
//属性名和properties文件中的名字一样
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
1.3.7、使用ApplicationContext
获取容器对象:SpringApplication.run(Springboot04MvcApplication.class, args);返回值是ApplicationContext。
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
//ConfigurableApplicationContext接口继承ApplicationContext
public interface ConfigurableApplicationContext extends ApplicationContext
1.3.8、CommandLineRunner和ApplicationRunner接口
这两个接口都有run方法,执行时间是在容器创建好后会自动运行run方法。故可以在该方法中定义需要在容器对象创建好完成的东西。
1.4、SpringBoot和web组件
1.4.1、springboot拦截器
拦截器是springmvc中的一个对象,能拦截对controller的请求。
拦截器框架中有系统的拦截器,还有自定义的拦截器,实现对请求的预处理。
1、springmvc拦截器步骤见springmvc教程。
2、springboot拦截器实现步骤
1、创建实现HandlerIntercepter接口的拦截器的类
@Component
public class MyIntercept implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
}
2、创建mvc的配置文件类
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private HandlerInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//excludePathPatterns方法表示不拦截的地址
String excludePathPatterns ="/user/login";
//addPathPatterns表示需要拦截的地址
String pathPatterns ="/user/**";
registry.addInterceptor(interceptor).excludePathPatterns(excludePathPatterns)
.addPathPatterns(pathPatterns);
}
}
1.4.2、Servlet
使用步骤:
1、创建Servlet类,继承HttpServlet
@Component
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("servlet测试");
writer.flush();
writer.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2、注册servlet,让框架找到servlet
@Bean
public ServletRegistrationBean servletRegist(){
//第一个参数是继承了HttpServlet的类,第二个参数是匹配的uri地址
ServletRegistrationBean registrationBean =new ServletRegistrationBean(servlet,"/myservlet");
return registrationBean;
}
1.4.3、Filter
过滤器filter是servlet规范中的,可以处理请求和响应。可以处理字符集编码
框架中使用过滤器:
1、创建过滤器类
@Component
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行过滤器");
filterChain.doFilter(servletRequest,servletResponse );
}
}
2、注册过滤器类
@Bean
public FilterRegistrationBean filterRegistration(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.addUrlPatterns("/user/*");
filterRegistrationBean.setFilter(filter);
return filterRegistrationBean;
}
}
1.4.4、字符集过滤器
1.4.4.1、自定义字符集过滤器
步骤:
1、注册字符集过滤器CharacterEncodingFilter
@Bean
public FilterRegistrationBean encordingFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("utf-8");
filter.setForceRequestEncoding(true);
filter.setForceResponseEncoding(true);
filterRegistrationBean.setFilter(filter);
filterRegistrationBean.addUrlPatterns("/*");
System.out.println("字符集过滤器经过了");
return filterRegistrationBean;
}
2、配置文件修改不适用默认的字符集过滤器
#springboot框架中字符集过滤器默认是配置好的,编码规则是ISO-8859-1
server.servlet.encoding.enabled=false
1.4.4.2、使用系统过滤器
#springboot框架中字符集过滤器默认是配置好的,编码规则是ISO-8859-1
server.servlet.encoding.enabled=true
server.servlet.encoding.charset=utf-8
#指定request和response都使用设定的字符集规则
server.servlet.encoding.force=true
1.5、ORM操作数据库
springboot集成了mybatis
1、mybatis起步依赖:完成把mybatis对象自动配置,对象放到容器中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、pom.xml文件指定把src/main/java目录中的xml文件放到classpath中
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>**/*.xml</includes>
</resource>
</resources>
</build>
3、创建实体类
4、创建mapper接口
/**
* @Mapper接口放在dao接口上面,作用是创建接口的代理类
*/
//@Mapper
public interface StudentDao {
Student selectStudentById(Integer id);
}
5、创建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="com.jfs.dao.StudentDao">
<select id="selectStudentById" resultType="com.jfs.pojo.Student">
select id,name,age from student where id=#{id}
</select>
</mapper>
6、创建service层,调用dao对象
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public Student selectStudent(Integer id) {
return studentDao.selectStudentById(id);
}
}
7、 创建controller层,调用service对象
@Controller
@RequestMapping("student")
public class MyController {
@Autowired
private StudentService service;
@RequestMapping("selectStudent")
@ResponseBody
public String selectStudent(){
Student student = service.selectStudent(2);
return student.toString();
}
}
8、编写application.properties配置文件,配置数据库连接信息。
spring.datasource.url=jdbc:mysql://47.102.110.12:3306/mybatistest?useSSL=false
#mysql最新的驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=eb7ecd2c8942412d
server.port=9090
server.servlet.context-path=/orm
1.5.1 @MapperScan
@MapperScan放在启动类上面表示扫描mapper接口的包。
1.5.2、mapper和dao分开管理
1、在resource目录下新建mapper文件加,把xml文件放到该目录中
2、在配置文件中配置xml文件所在的位置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
1.5.3、spring事务控制
springboot使用事务:
1、 在业务方法上加@Transactional注解,放在公共事务之上。
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public Student selectStudent(Integer id) {
return studentDao.selectStudentById(id);
}
@Transactional
@Override
public void insertStudent(Student student) {
studentDao.insertStudent(student);
}
}
2、在主启动类上,加入@EnableTransactionManagement,表示启用事务管理器。
@MapperScan("com.jfs.dao")
@SpringBootApplication
@EnableTransactionManagement
public class Springboot05Application {
public static void main(String[] args) {
SpringApplication.run(Springboot05Application.class, args);
}
}
1.6、接口架构风格-Restful
1.6.1、认识Rest
接口:可以值访问servlet、controller的uri,或者是调用其他程序的函数
架构风格:
1、传统风格:https://www.bilibili.com/video/BV1XQ4y1m7ex?p=57&spm_id_from=pageDriver
2、RestFul风格:是一种接口的架构风格和设计理念,不是一种标准。
1、优点:简洁、有层次
2、rest中的要素:用rest表示资源和对资源的操作。在互联网中表示一个资源或者一个操作。
资源用url表示,在互联网中,使用的图片、视频、文本、网页等等都是资源。资源用名词表示
对资源:
1、查询资源
2、修改资源
3、删除资源
4、删除资源
资源用url表示,通过名词表达资源。
使用http中的动作(请求方式),表示对资源的操作(CRUD)。
GET :查询资源
Post:创建资源
Put:更新资源
Delete·:删除资源
一句话说明Rest:使用url表示资源,通过http动作操作资源。
1.6.2、RestFul的注解
@PathVariable:获取url数据
@PostMapping:接收和处理post方式的请求,相当于@RequestMapping(method = RequestMethod.POST )
@GetMapping:支持get请求方式,相当于@RequestMapping(method = RequestMethod.GET )
@PutMapping:接收和处理post方式的请求,相当于@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping:支持get请求方式,相当于@RequestMapping(method = RequestMethod.DELETE)
@RestController:复合注解,是@Controller和@ResponseBody组合。
在类上使用@RestController表示该类所有的方法都加上了@ResponseBody注解。
@RestController
@RequestMapping("/user")
public class MyRestController {
//当路径名和形参名一样时@PathVariable注解value值可以省略
@RequestMapping("/{id}")
public String rest(@PathVariable("id") Integer id){
return "获取到的id是"+id;
}
}
1.6.3、在页面中或者ajax中支持put和delete请求
在springmvc中,有一个过滤器,可以把put ,delete请求转换成post请求。
实现步骤:
1、在配置文件中开启使用HiddenHttpMethodFilter过滤器
#支持使用put,delete请求。
spring.mvc.hiddenmethod.filter.enabled=true
2、在请求页面中,包含_method参数,他的值是put,delete。发起请求使用的post请求。
<form method="post" action="user/203">
<input type="hidden" name="_method" value="put">
<input type="submit" value="提交">
</form>
1.7、Springboot集成Redis
Redis:一个Nosql数据库,常用于缓存。
Redis数据类型:String,set ,zset, list ,hash
Spring、Springboot中有一个Redistemplate(或者StringRedistemplate),处理和Redis交互。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)