SpringBoot学习笔记整理
SpringBoot
第一章JavaConfig
1.为什么要使用 Spring Boot
因为Spring, SpringMVC 需要使用的大量的配置文件 (xml文件)
还需要配置各种对象,把使用的对象放入到spring容器才能使用对象。
2.SpringBoot 就相当于 不需要配置文件的Spring+SpringMVC。 常用的框架和第三方库都已经配置好了。
拿来就可以使用了。
3.SpringBoot开发效率高,使用方便多了
1.1JavaConfig
使用java类作为xml配置文件的替代,是配置spring容器的纯java方式。在这个java类中可以创建java对象,把对象放入spring容器中(注入到容器)。
使用两个注解:
1)@Configuration:放在一个类的上面,表示这个类是作为配置文件使用的
2)@Bean:声明对象,把对象注入到容器中。
例子:
package com.bjpowernode.config;
import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的
* 位置:在类的上面
*
* SpringConfig这个类就相当于beans.xml
*/
@Configuration
public class SpringConfig {
/**
* 创建方法,方法的返回值是对象。 在方法的上面加入@Bean
* 方法的返回值对象就注入到容器中。
*
* @Bean: 把对象注入到spring容器中。 作用相当于<bean>
*
* 位置:方法的上面
*
* 说明:@Bean,不指定对象的名称,默认是方法名是 id
*
*/
@Bean
public Student createStudent(){
Student s1 = new Student();
s1.setName("张三");
s1.setAge(26);
s1.setSex("男");
return s1;
}
/***
* 指定对象在容器中的名称(指定<bean>的id属性)
* @Bean的name属性,指定对象的名称(id)
*/
@Bean(name = "lisiStudent")
public Student makeStudent(){
Student s2 = new Student();
s2.setName("李四");
s2.setAge(22);
s2.setSex("男");
return s2;
}
}
1.2@ImporResource
@ImportResource 作用导入其他的xml配置文件, 等于 在xml
@Configuration
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
public class SpringConfig {
}
1.3@PropertyResource
@PropertyResource:读取properties属性配置文件。使用属性配置文件可以实现外部化配置 ,
在程序代码之外提供数据。
步骤:
- 在resources目录下,创建properties文件, 使用k=v的格式提供数据
- 在PropertyResource 指定properties文件的位置
- 使用@Value(value=“${key}”)
@Configuration
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.bjpowernode.vo")
public class SpringConfig {
}
第二章Spring Boot
##2.1创建Spring Boot项目
使用Spring提供的初始化器, 就是向导创建SpringBoot应用
SpringBoot项目的结构:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dVQqfeOR-1678258882780)(E:\assets\image-20210115152427829.png)]
2.2注解的使用
@SpringBootApplication
符合注解:由
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
1.@SpringBootConfiguration
@Configuration
public @interface SpringBootConfiguration {
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}
说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用的,
可以使用Bean声明对象,注入到容器
2.@EnableAutoConfiguration
启用自动配置, 把java对象配置好,注入到spring容器中。例如可以把mybatis的对象创建好,放入到容器中
3.@ComponentScan
@ComponentScan 扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等。
默认扫描的包: @ComponentScan所在的类所在的包和子包。
2.3SpringBoot的配置文件
配置文件名称: application
扩展名有: properties( k=v) ; yml ( k: v)
使用application.properties, application.yml
例1:application.properties设置 端口和上下文
#设置端口号
server.port=8082
#设置访问应用上下文路径, contextpath
server.servlet.context-path=/myboot
例2: application.yml
server:
port: 8083
servlet:
context-path: /myboot2
2.4@ConfigurationProperties
@ConfigurationProperties: 把配置文件的数据映射为java对象。
属性:prefix 配置文件中的某些key的开头的内容。
@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
private String name;
private String website;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot
#自定义key=value
school.name=动力节点
school.website=www.bjpowernode.com
school.address=北京的大兴区
site=www.bjpowernode.com
2.5ComnandLineRunner 接口 , ApplcationRunner接口
这两个接口都 有一个run方法。 执行时间在容器对象创建好后, 自动执行run()方法。
可以完成自定义的在容器对象创建好的一些操作。
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
第三章Web组件
3.1拦截器
拦截器是SpringMVC中一种对象,能拦截器对Controller的请求。
拦截器框架中有系统的拦截器, 还可以自定义拦截器。 实现对请求预先处理。
实现自定义拦截器:
1.创建类实现SpringMVC框架的HandlerInterceptor接口
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
2.需在SpringMVC的配置文件中,声明拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:path="url" />
<bean class="拦截器类全限定名称"/>
</mvc:interceptor>
</mvc:interceptors>
SpringBoot中注册拦截器:
@Configuration
public class MyAppConfig implements WebMvcConfigurer {
//添加拦截器对象, 注入到容器中
@Override
public void addInterceptors(InterceptorRegistry registry) {
//创建拦截器对象
HandlerInterceptor interceptor = new LoginInterceptor();
//指定拦截的请求uri地址
String path []= {"/user/**"};
//指定不拦截的地址
String excludePath [] = {"/user/login"};
registry.addInterceptor(interceptor)
.addPathPatterns(path)
.excludePathPatterns(excludePath);
}
}
3.2 Servlet
在SpringBoot框架中使用Servlet对象。
使用步骤:
- 创建Servlet类。 创建类继承HttpServlet
- 注册Servlet ,让框架能找到Servlet
3.3过滤器Filter
Filter是Servlet规范中的过滤器,可以处理请求, 对请求的参数, 属性进行调整。 常常在过滤器中处理字符编码
在框架中使用过滤器:
- 创建自定义过滤器类
- 注册Filter过滤器对象
// 自定义过滤器
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行了MyFilter,doFilter ");
filterChain.doFilter(servletRequest,servletResponse);
}
}
注册Filter
@Configuration
public class WebApplicationConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter( new MyFilter());
bean.addUrlPatterns("/user/*");
return bean;
}
}
第四章 ORM操作MySQL
使用MyBatis框架操作数据, 在SpringBoot框架集成MyBatis
使用步骤:
-
mybatis起步依赖 : 完成mybatis对象自动配置, 对象放在容器中
-
pom.xml 指定把src/main/java目录中的xml文件包含到classpath中
-
创建实体类Student
-
创建Dao接口 StudentDao , 创建一个查询学生的方法
-
创建Dao接口对应的Mapper文件, xml文件, 写sql语句
-
创建Service层对象, 创建StudentService接口和他的实现类。 去dao对象的方法。完成数据库的操作
-
创建Controller对象,访问Service。
-
写application.properties文件
配置数据库的连接信息。
第一种方式 : @Mapper
/**
* @Mapper:告诉MyBatis这是dao接口,创建此接口的代理对象。
* 位置:在类的上面
*/
@Mapper
public interface StudentDao {
Student selectById(@Param("stuId") Integer id);
}
第二种方式 @MapperScan
/**
* @MapperScan: 找到Dao接口和Mapper文件
* basePackages:Dao接口所在的包名
*/
@SpringBootApplication
@MapperScan(basePackages = {"com.bjpowernode.dao","com.bjpowernode.mapper"})
public class Application {
}
第三种方式: Mapper文件和Dao接口分开管理
现在把Mapper文件放在resources目录下
1)在resources目录中创建子目录 (自定义的) , 例如mapper
2)把mapper文件放到 mapper目录中
3)在application.properties文件中,指定mapper文件的目录
- 在pom.xml中指定 把resources目录中的文件 , 编译到目标目录中
第四个 事务
Spring框架中的事务:
1) 管理事务的对象: 事务管理器(接口, 接口有很多的实现类)
例如:使用Jdbc或mybatis访问数据库,使用的事务管理器:DataSourceTransactionManager
2 ) 声明式事务: 在xml配置文件或者使用注解说明事务控制的内容
控制事务: 隔离级别,传播行为, 超时时间
3)事务处理方式:
1) Spring框架中的@Transactional
2) aspectj框架可以在xml配置文件中,声明事务控制的内容
SpringBoot中使用事务: 上面的两种方式都可以。
1)在业务方法的上面加入@Transactional , 加入注解后,方法有事务功能了。
2)明确的在 主启动类的上面 ,加入@EnableTransactionManager
/**
* @Transactional: 表示方法的有事务支持
* 默认:使用库的隔离级别, REQUIRED 传播行为; 超时时间 -1
* 抛出运行时异常,回滚事务
*/
@Transactional
@Override
public int addStudent(Student student) {
System.out.println("业务方法addStudent");
int rows = studentDao.insert(student);
System.out.println("执行sql语句");
//抛出一个运行时异常, 目的是回滚事务
//int m = 10 / 0 ;
return rows;
}
第五章 接口架构风格 —RESTful
接口: API(Application Programming Interface,应用程序接口)是一些预先定义的接口(如函数、HTTP接口),或指软件系统不同组成部分衔接的约定。 用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节.
接口(API): 可以指访问servlet, controller的url, 调用其他程序的函数.
架构风格: api组织方式(样子)
就是一个传统的: http://localhost:9002/mytrans/addStudent?name=lisi&age=26
在地址上提供了 访问的资源名称addStudent, 在其后使用了get方式传递参数。
5.1 REST
RESTful架构风格
1)REST : (英文: Representational State Transfer , 中文: 表现层状态转移)。
REST:是一种接口的架构风格和设计的理念,不是标准。
优点: 更简洁,更有层次
表现层状态转移:
表现层就是视图层, 显示资源的, 通过视图页面,jsp等等显示操作资源的结果。
状态: 资源变化
转移: 资源可以变化的。 资源能创建,new状态, 资源创建后可以查询资源, 能看到资源的内容,
这个资源内容 ,可以被修改, 修改后资源 和之前的不一样。
2)REST中的要素:
用REST表示资源和对资源的操作。 在互联网中,表示一个资源或者一个操作。
资源使用url表示的, 在互联网, 使用的图片,视频, 文本,网页等等都是资源。
资源是用名词表示。
资源使用url表示,通过名词表示资源。
在url中,使用名词表示资源, 以及访问资源的信息, 在url中,使用“ / " 分隔对资源的信息
http://localhost:8080/myboot/student/1001
使用http中的动作(请求方式), 表示对资源的操作(CURD)
GET: 查询资源 – sql select
处理单个资源: 用他的单数方式
http://localhost:8080/myboot/student/1001
http://localhost:8080/myboot/student/1001/1
处理多个资源:使用复数形式
http://localhost:8080/myboot/students/1001/1002
POST: 创建资源 – sql insert
http://localhost:8080/myboot/student
在post请求中传递数据
PUT: 更新资源 – sql update
DELETE: 删除资源 – sql delete
3) 一句话说明REST:
使用url表示资源 ,使用http动作操作资源。
- 注解
@PathVariable : 从url中获取数据(项目中经常用到)
@GetMapping: 支持的get请求方式, 等同于 @RequestMapping( method=RequestMethod.GET)
@PostMapping: 支持post请求方式 ,等同于 @RequestMapping( method=RequestMethod.POST)
@PutMapping: 支持put请求方式, 等同于 @RequestMapping( method=RequestMethod.PUT)
@DeleteMapping: 支持delete请求方式, 等同于 @RequestMapping( method=RequestMethod.DELETE)
@RestController: 符合注解, 是@Controller 和@ResponseBody组合。
在类的上面使用@RestController , 表示当前类者的所有方法都加入了 @ResponseBody
-
Postman : 测试工具
使用Postman : 可以测试 get ,post , put ,delete 等请求
5.2 在页面中或者ajax中,支持put,delete请求
在SpringMVC中 有一个过滤器, 支持post请求转为put ,delete
过滤器: org.springframework.web.filter.HiddenHttpMethodFilter
作用: 把请求中的post请求转为 put , delete
实现步骤:
- application.properties(yml) : 开启使用 HiddenHttpMethodFilter 过滤器
- 在请求页面中,包含 _method参数, 他的值是 put, delete , 发起这个请求使用的post方式
第六章 总结
注解
创建对象的:
@Controller: 放在类的上面,创建控制器对象,注入到容器中
@RestController: 放在类的上面,创建控制器对象,注入到容器中。
作用:复合注解是@Controller , @ResponseBody, 使用这个注解类的,里面的控制器方法的返回值 都是数据
@Service : 放在业务层的实现类上面,创建service对象,注入到容器
@Repository : 放在dao层的实现类上面,创建dao对象,放入到容器。 没有使用这个注解,是因为现在使用MyBatis框架,dao对象是MyBatis通过代理生成的。 不需要使用@Repository、 所以没有使用。
@Component: 放在类的上面,创建此类的对象,放入到容器中。
赋值的:
@Value : 简单类型的赋值, 例如 在属性的上面使用@Value("李四") private String name
还可以使用@Value,获取配置文件者的数据(properties或yml)。
@Value("${server.port}") private Integer port
@Autowired: 引用类型赋值自动注入的,支持byName, byType. 默认是byType 。 放在属性的上面,也可以放在构造 方法的上面。 推荐是放在构造方法的上面
@Qualifer: 给引用类型赋值,使用byName方式。
@Autowird, @Qualifer都是Spring框架提供的。
@Resource : 来自jdk中的定义, javax.annotation。 实现引用类型的自动注入, 支持byName, byType.
默认是byName, 如果byName失败, 再使用byType注入。 在属性上面使用
其他:
@Configuration : 放在类的上面,表示这是个配置类,相当于xml配置文件
@Bean:放在方法的上面, 把方法的返回值对象,注入到spring容器中。
@ImportResource : 加载其他的xml配置文件, 把文件中的对象注入到spring容器中
@PropertySource : 读取其他的properties属性配置文件
@ComponentScan: 扫描器 ,指定包名,扫描注解的
@ResponseBody: 放在方法的上面,表示方法的返回值是数据, 不是视图
@RequestBody : 把请求体中的数据,读取出来, 转为java对象使用。
@ControllerAdvice: 控制器增强, 放在类的上面, 表示此类提供了方法,可以对controller增强功能。
@ExceptionHandler : 处理异常的,放在方法的上面
@Transcational : 处理事务的, 放在service实现类的public方法上面, 表示此方法有事务
SpringBoot中使用的注解
@SpringBootApplication : 放在启动类上面, 包含了@SpringBootConfiguration
@EnableAutoConfiguration, @ComponentScan
MyBatis相关的注解
@Mapper : 放在类的上面 , 让MyBatis找到接口, 创建他的代理对象
@MapperScan :放在主类的上面 , 指定扫描的包, 把这个包中的所有接口都创建代理对象。 对象注入到容器中
@Param : 放在dao接口的方法的形参前面, 作为命名参数使用的。
Dubbo注解
@DubboService: 在提供者端使用的,暴露服务的, 放在接口的实现类上面
@DubboReference: 在消费者端使用的, 引用远程服务, 放在属性上面使用。
@EnableDubbo : 放在主类上面, 表示当前引用启用Dubbo功能。
lerAdvice: 控制器增强, 放在类的上面, 表示此类提供了方法,可以对controller增强功能。
@ExceptionHandler : 处理异常的,放在方法的上面
@Transcational : 处理事务的, 放在service实现类的public方法上面, 表示此方法有事务
SpringBoot中使用的注解
@SpringBootApplication : 放在启动类上面, 包含了@SpringBootConfiguration
@EnableAutoConfiguration, @ComponentScan
MyBatis相关的注解
@Mapper : 放在类的上面 , 让MyBatis找到接口, 创建他的代理对象
@MapperScan :放在主类的上面 , 指定扫描的包, 把这个包中的所有接口都创建代理对象。 对象注入到容器中
@Param : 放在dao接口的方法的形参前面, 作为命名参数使用的。
Dubbo注解
@DubboService: 在提供者端使用的,暴露服务的, 放在接口的实现类上面
@DubboReference: 在消费者端使用的, 引用远程服务, 放在属性上面使用。
@EnableDubbo : 放在主类上面, 表示当前引用启用Dubbo功能。