第一章 xml和JavaConfig(xml的替代)
xml: 是spring在3.0之前作为容器的配置文件
javaConfig:在 3.0之后就使用了Java类做配置文件使用
什么是javaConfig
定义:是spring提供使用的类配置容器,配置springIOC容器的纯Java方法
优点:
1.可以使用面向对象的方式, 一个配置类可以继承配置类,可以重写方法
2.避免繁琐的 xml 配置
作用:javaConfig是xml的另外一种的表现形式,用Java类来完成xml的工作,在这个java类中可以(1)创建Java对象( )
(2)Java对象放入到spring容器中(注入到spring容器中,类似于组件扫描器)
spring中使用注解替代xml语法
@Configuration:
位置:在类的上面
作用:放在一个类上面,声明这个类是作为配置文件使用
1@Bean:
作用:声明对象,把对象放到spring容器中。
位置:在方法上面
属性:name,说明 中的id
注意如果@Bean不指定对象的名称的话,,默认就是方法名称就是默认bean的id,
案例:
@Configuration // 表明这个类相当于bean.xml
public class SpirngConfig{
@Bean
public Student createStudent() {
Student s1 = new Student();
s1.setName("张三“);
s1.setAge(32)
}
@Bean(name="lisiStudent")
public Student makeStudent(){
Student s2 = new Student();
s2.setName("李四");
s2.setAge(22);
s2.setSex("男");
return s2;
}
}
2@ImporResource
作用:在javaConfig类中导入其他的xml的配置文件,可以加载并且创建Java对象(类似)
案例
@Configuration
@ImportResource(value"{classpath:applicationContext.xml",classpath:beans.xml"})
public class SpringConfig{
}
3,@PropertyResource
作用:读取properties属性的配置文件,在程序代码之外给提供数据
步助:
-在resources目录下,创建properties文件, 使用k=v的格式提供数据
-在PropertyResource 指定properties文件的位置
- 使用@Value(value="${key})
- @ComponentScan(basePackages=“com.vo”) 扫描组件,通知spring容器创建对象
案例:
@Configuration
@ImportResource(value={"classspath:beans.xml"}
@PropertySource(value="classpath:config.properties")
@ComponentScan(basePackages="com.vo")
public class SpringConfig {
}
第二章spirngboot简介
springboot定义:springboot是spring的一员,可以简化spring和springmvc的使用,核心还是ioc容器
特点:
1.创建spring应用
2.内嵌入了tomcat,jetty,undertwo等服务器
3.提供了starter起步依赖,简化应用的配置 例如 :使用MyBatis框架 , 需要在Spring项目中,配置MyBatis的对象 SqlSessionFactory , Dao的代理对象,而在在SpringBoot项目中,在pom.xml里面, 加入一个 mybatis-spring-boot-starter依赖,就可以自动的创建。
4,尽可能去配置spring和第三方库。叫做自动配置(就是把spring中的,第三方库中的对象都创建好,放到容器中, 开发人员可以直接使用)
5.不用生成代码, 不用使用xml,做配置
springboot目录解释
默认删除了的目录解释
mvn,HELP.md,mvnw,mvnw.cmd, :maven仓库的相关配置我们一般用不到,就给删除了。
springBoot 注解的使用
1.@SpringBootApplication
复合注解:由:
@SpringBootConfiguration :在类上出现可以表示的该类可以作为配置文件使用的,并且可以使用bean对象注入到容器中。
@EnableAutoConfiguration:启动自动配置,把Java对象配置号,注入到spring容器中,例如可以把mybatis的对象创建好,放入到容器中
@ComponentScan 扫描器,找到注解,根据注解创建对象,给属性赋值等等,默认扫描的包是@ComponentScan的类所在的包和子包。
以上三个注解组成,就有了他们注解的功能
1,使用bean创建对象注入容器
2.自动配置对象,注入到spring容器
3.扫描器,创建对象赋值
所以我们在创建类的包和类的时候,尽量和.@SpringBootApplication 注解所在的类在同一个文件夹下。
spirngBoot核心配置文件
springBoot的核心配置文件,作用是配置springBoot程序,名字必须是application开始
配置文件的作用
(1)数据库的连接信息
(2)项目的启动端口
(3)第三⽅系统的调⽤秘钥等信息
(4)⽤于发现和定位问题的普通⽇志和异常⽇志等
配置文件类型
- .properties 文件(默认采用该文件,k=v) application.properties
文件特点是采用的是k=v的形式,多级目录是采用”."的形式隔开,一个“点”表示文件夹的一级
例子1 application.properties配置端口号和上下文
#设置端口号
server.port=8082
#设置应用访问上下文 contextPath
searver.servlet.contxt-path=/myboot
- yml ( k: v), application.yml
文件的特点是,yml是采取层级式的关系,一层一个空格隔开
server:
port: 8003
servlet:
context-path:/myboot2
第一个springBoot的hello world
第一步配置springboot核心配置,application.properties
server.port=8089
server.servlet.context-path=/myboot
程序的入口
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class,args);
}
}
控制器,处理请求的
package com.contrl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloSpirngBoot {
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "springBootSayHello";
}
}
运行结果
多环境配置
定义:多环境是指 开发环境, 测试环境, 上线的环境,每个环境有不同的配置信息, 例如端口, 上下文件, 数据库url,用户名,密码等等
优点:使用多环境配置文件,可以方便的切换不同的配置。
使用的方式:
创建多个配置文件, 名称规则:
application-环境名称.properties(yml)
创建开发环境的配置文件: application-dev.properties( application-dev.yml )
创建测试者使用的配置: application-test.properties
案例
开发环境
上线环境
默认加载主配置文件,选择那一个环境配置
配置文件的数据映射为java对象
@ConfigurationProperties
作用把配置文件中的数据映射为Java对象
属性:prefix 配置文件中的某些key的开头的内容。
要求:
配置文件中的key必须和对象属性的id保持一致才可以的(它的底层是调用了属性的set的方式注入
结果
案例
application.properties
#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot
#自定义key=value
school.name=xawl
school.website=www.xawl.com
school.address=高新区
site=www.xawl.com
案例:
@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) {
System.out.println("school的setName调用了");
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;
}
@Override
public String toString() {
return "SchoolInfo{" +
"name='" + name + '\'' +
", website='" + website + '\'' +
", address='" + address + '\'' +
'}';
}
}
配置文件读取信息造成中文乱码
1,一般在配置文件中,不建议出现中文(注释除外)
2,如果有,可以先转化为 ASCII 码
ideal改变properties文件编码
设置完成后新建properties文件,新建文件后支持编码格式,原来的并没有具备,删除原来的文件。
springBoot中使用jsp
说明:SpringBoot不推荐使用jsp ,而是使用模板技术代替jsp
使用的步助
1)加入处理jsp的依赖,负责编译jsp文件(把jsp文件渲染成html文件)
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
2)如果要使用servlet,jsp,jstl等功能添加对应的依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
3)在 pom.xml 的 build 标签中要配置以下信息
SpringBoot 要求 jsp 文件必须编译到指定的 META-INF/resources 目录下才能访问,否则访问不到
<!—
SpringBoot 要求 jsp 文件必须编译到指定的
META-INF/resources 目录下才能访问,否则访问不到。
其它官方已经建议使用模版技术(后面会课程会单独讲解模版技
术)
-->
<resources>
<resource>
<!--源文件位置-->
<directory>src/main/webapp</directory>
<!--指定编译到META-INF/resource,该目录不能随便写-->
<targetPath>META-INF/resources</targetPath>
<!--指定要把哪些文件编译进去,**表示 webapp 目录及子
目录,*.*表示所有文件-->
<includes>
<include>**/*.*</include>
</includes>
</resource>
4)配置视图解析器,相当于springMVC的设置
在 application.properties 文件配置 Spring MVC 的视图展示为jsp,这里相当于 Spring MVC 的配置
配置 SpringMVC 的视图解析器
#其中:/相当于 src/main/webapp 目录
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
- 编写controller类
@Controller
public class SpringBootController {
@RequestMapping(value = "/springBoot/jsp")
public String jsp(Model model) {
model.addAttribute("data","SpringBoot 前端使用 JSP页面!");
return "index";
}
}
6)src/main 下创建一个 webapp 目录,然后在该目录下新建
index.jsp 页面
如果在webapp目录下右键,没有创建jsp的选项,可以在Project Structure中指定webapp
为 Web Resource Directory
7)在jsp中获取controller传递过来的数据
8)结果
在springboot中使用ApplicationContext
在 main 方法中 SpringApplication.run()方法获取返回的 Spring 容器对象,再获取业务 bean
进行调用.
原理:
返回值ConfigurableApplicationContext 的部分源码
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
由上面的源码分析可以知道,ConfigurableApplicationContext接口时ApplicationContext的子接口
public interface ConfigurableApplicationContext extends ApplicationContext
所以在使用的时候我们就可以去使用它的父接口,获得,spring容器中的对象。
ComnandLineRunner 接口 , ApplcationRunner接口
这两个接口都有一个run方法,执行时间是在容器创建对象好了之后,自动执行run方法(可以理解为,在main方法里面调用了run方法)
目的:可以完成一些容器对象创建好的一些操作
案例
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
案例
@SpringBootApplication
public class Application implements CommandLineRunner {
@Resource
private HelloService helloService;
public static void main(String[] args) {
System.out.println("准备创建容器对象");
//创建容器对象
SpringApplication.run(Application.class, args);
System.out.println("容器对象创建之后");
}
@Override
public void run(String... args) throws Exception {
String str = helloService.sayHello("lisi");
System.out.println("调用容器中的对象="+str);
//可做自定义的操作,比如读取文件, 数据库等等
System.out.println("在容器对象创建好,执行的方法");
}
}
ApplicationRunner接口类似
第三章Web组件
重要的组件 :拦截器,servlet,Filter
拦截器
作用:拦截器是springmvc的一种对象,能够拦截Conroller请求
拦截器框架中有系统的拦截器, 还可以自定义拦截器。 实现对请求预先处理。
实现自定义拦截器:
创建类实现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);
}
}
Spring Boot 中使用 Servlet
ServletRegistrationBean 用来做在 servlet 3.0+容器中注册 servlet 的功能,但更具有
SpringBean 友好性。
在SpringBoot框架中使用Servlet对象。
使用步骤
1)创建Servlet类。 创建类继承HttpServlet
2)1. 注册Servlet ,让框架能找到Servlet
案例
//创建Servlet类
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//使用HttpServletResponse输出数据,应答结果
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("===执行的是Servlet==");
out.flush();
out.close();
}
}
2)注册Servlet
@Configuration
public class WebApplictionConfig {
//定义方法, 注册Servlet对象
@Bean
public ServletRegistrationBean servletRegistrationBean(){
//public ServletRegistrationBean(T servlet, String... urlMappings)
//第一个参数是 Servlet对象, 第二个是url地址
//ServletRegistrationBean bean =
//new ServletRegistrationBean( new MyServlet(),"/myservlet");
ServletRegistrationBean bean = new ServletRegistrationBean();
bean.setServlet( new MyServlet());
bean.addUrlMappings("/login","/test"); // <url-pattern>
return bean;
}
}
Spring Boot 中使用 Filter
FilterRegistrationBean 用来注册 Filter 对象
1.创建 Filter 对象
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException,
ServletException {
System.out.println("使用了 Servlet 中的 Filter 对象");
filterChain.doFilter(servletRequest,servletResponse);
}
}
2.注册 Filter
@Configuration
public class SystemConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean reg = new FilterRegistrationBean();
//使用哪个过滤器
reg.setFilter( new MyFilter());
//过滤器的地址
@Configuration
public class SystemConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean reg = new FilterRegistrationBean();
//使用哪个过滤器
reg.setFilter( new MyFilter());
//过滤器的地址
3.创建 Controller
@Controller
public class FilterController {
@RequestMapping("/user/account")
@ResponseBody
public String hello(){
return "/user/account";
}
@RequestMapping("/query")
@ResponseBody
public String doSome(){
return "/query";
}
}
字符集过滤器的应用
作用:CharacterEncodingFilter : 解决post请求中乱码的问题
在SpringMVC框架, 在web.xml 注册过滤器。 配置他的属性
1.创建 Servlet,输出中文数据
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("学习 Hello SpringBoot 框架,自动配置");
out.flush();
out.close();
}
}
2)注册 Servlet 和 Filter
pringframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
@Configuration
public class SystemAppliationConfig {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean reg = new ServletRegistrationBean(new
MyServlet(),"/myservlet");
return reg;
}
//注册 Filter
//@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean reg = new FilterRegistrationBean();
//创建 CharacterEncodingFilter
CharacterEncodingFilter filter = new CharacterEncodingFilter();
//设置 request, response 使用编码的值
filter.setEncoding("utf-8");
//强制 request, response 使用 encoding 的值
filter.setForceEncoding(true);
reg.setFilter(filter);
//请求先使用过滤器处理
reg.addUrlPatterns("/*");
return reg;
}
}
3.在 application.properties , 禁用 Spring Boot 中默认启用的过滤器
#启用自己的 CharacterEncodingFitler 的设置
#SpringBoot中默认已经配置了CharacterEncodingFilter。 编码默认ISO-8859-1
#设置enabled=false 作用是关闭系统中配置好的过滤器, 使用自定义的CharacterEncodingFilter
server.servlet.encoding.enabled=false
第二种方式
修改application.properties文件
server.port=9001
server.servlet.context-path=/myboot
#让系统的CharacterEncdoingFilter生效
server.servlet.encoding.enabled=true
#指定使用的编码方式
server.servlet.encoding.charset=utf-8
#强制request,response都使用charset属性的值
server.servlet.encoding.force=true