- SpringBoot
- 第一章 JavaConfig
- 1.1 JavaConfig
- 1.2 [@ImporResource ](/ImporResource )
- 1.3 [@PropertyResource ](/PropertyResource )
- 第二 章 Spring Boot
- 2.1 介绍
- 2.2 创建Spring Boot项目
- 2.2.1 第一种方式, 使用Spring提供的初始化器, 就是向导创建SpringBoot应用
- 2.2.1 使用国内的地址
- 2.3 注解的使用
- @SpringBootApplication
- 1.@SpringBootConfiguration
- 2.@EnableAutoConfiguration
- 3.[@ComponentScan ](/ComponentScan )
- 2.4 SpringBoot的配置文件
- 2.5 多环境配置
- 2.6 @ConfigurationProperties
- 2.7 使用jsp
- 2.8 使用容器
- 2.9 ComnandLineRunner 接口 , ApplcationRunner接口
- 第三章 Web组件
- 3.1 拦截器
- 3.2 Servlet
- 3.3 过滤器Filter
- 3.4 字符集过滤器
- 路径中的*
- / 和
@Configuration
public class SpringConfig {
@Bean
public Student createStudent(){
Student s1 = new Student();
s1.setName("张三");
s1.setAge(26);
s1.setSex("男");
return s1;
}
@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 介绍SpringBoot是Spring中的一个成员, 可以简化Spring,SpringMVC的使用。 他的核心还是IOC容器。
特点:
- Create stand-alone Spring applications
创建spring应用 - Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
内嵌的tomcat, jetty , Undertow - Provide opinionated ‘starter’ dependencies to simplify your build configuration
提供了starter起步依赖,简化应用的配置。
比如使用MyBatis框架 , 需要在Spring项目中,配置MyBatis的对象 SqlSessionFactory , Dao的代理对象
在SpringBoot项目中,在pom.xml里面, 加入一个 mybatis-spring-boot-starter依赖 - Automatically configure Spring and 3rd party libraries whenever possible
尽可能去配置spring和第三方库。叫做自动配置(就是把spring中的,第三方库中的对象都创建好,放到容器中, 开发人员可以直接使用) - Provide production-ready features such as metrics, health checks, and externalized configuration
提供了健康检查, 统计,外部化配置 - Absolutely no code generation and no requirement for XML configuration
不用生成代码, 不用使用xml,做配置
使用的地址: https://start.spring.io
SpringBoot项目的结构:
2.2.1 使用国内的地址https://start.springboot.io
2.3 注解的使用 @SpringBootApplication@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所在的类所在的包和子包。因为启动类Application.java是在主包下,而启动类上面的注解又包含@ComponentScan ,所以就可以不用配置@ComponentScan,只要把类放在正确的位置,就会自动扫描。
@ComponentScan 扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等。 默认扫描的包: @ComponentScan所在的类所在的包和子包。
2.4 SpringBoot的配置文件配置文件名称: application
扩展名有: properties( k=v) ; yml ( k: v)yml这种格式的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如果一个项目中同时有application.yml和 application.properties,会以application.properties为准,application.yml会失效
2.5 多环境配置有开发环境, 测试环境, 上线的环境。
每个环境有不同的配置信息, 例如端口, 上下文件, 数据库url,用户名,密码等等
使用多环境配置文件,可以方便的切换不同的配置。
使用方式: 创建多个配置文件, 名称规则: application-环境名称.properties(yml) (命名一定要根据这个规范)
创建开发环境的配置文件: application-dev.properties( application-dev.yml )
创建测试者使用的配置: application-test.properties
命名规范,下面激活使用的名字就直接写 - 后面的名字即可 #激活使用的test环境 spring: profiles: active: test2.6 @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; } @Override public String toString() { return "SchoolInfo{" + "name='" + name + ''' + ", website='" + website + ''' + ", address='" + address + ''' + '}'; } }application.properties
#配置端口号 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.7 使用jspSpringBoot不推荐使用jsp ,而是使用模板技术代替jsp
使用jsp需要配置:
1) 加入一个处理jsp的依赖。 负责编译jsp文件
org.apache.tomcat.embed tomcat-embed-jasper - 如果需要使用servlet, jsp,jstl的功能
javax.servlet jstl javax.servlet javax.servlet-api javax.servlet.jsp javax.servlet.jsp-api 2.3.1 -
创建一个存放jsp的目录,一般叫做webapp
index.jsp
-
需要在pom.xml指定jsp文件编译后的存放目录。
META-INF/resources
5)创建Controller, 访问jsp
6)在application.propertis文件中配置视图解析器
2.8 使用容器你想通过代码,从容器中获取对象。
通过SpringApplication.run(Application.class, args); 返回值获取容器。
public static ConfigurableApplicationContext run(Class> primarySource, String... args) { return run(new Class[]{primarySource}, args); } ConfigurableApplicationContext : 接口,是ApplicationContext的子接口 public interface ConfigurableApplicationContext extends ApplicationContext2.9 ComnandLineRunner 接口 , ApplcationRunner接口这两个接口都 有一个run方法。 执行时间在容器对象创建好后, 自动执行run()方法。
可以完成自定义的在容器对象创建好的一些操作。
@FunctionalInterface public interface CommandLineRunner { void run(String... args) throws Exception; } @FunctionalInterface public interface ApplicationRunner { void run(ApplicationArguments args) throws Exception; }package com.bjpowernode; import com.bjpowernode.service.HelloService; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.util.ResourceUtils; import javax.annotation.Resource; @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("在容器对象创建后,执行的方法"); } }第三章 Web组件讲三个内容: 拦截器, Servlet ,Filter
3.1 拦截器拦截器是SpringMVC中一种对象,能拦截器对Controller的请求。
拦截器框架中有系统的拦截器, 还可以自定义拦截器。 实现对请求预先处理。
实现自定义拦截器:
- 创建类实现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的配置文件中,声明拦截器
SpringBoot中注册拦截器:
@Configuration public class MyAppConfig implements WebMvcConfigurer { //添加拦截器对象, 注入到容器中 @Override public void addInterceptors(InterceptorRegistry registry) { //创建拦截器对象 HandlerInterceptor interceptor = new LoginInterceptor(); //指定拦截的请求uri地址 String path []= {"/user public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("执行了LoginInterceptor的preHandle"); return true; } }3.2 Servlet在SpringBoot框架中使用Servlet对象。
使用步骤:
- 创建Servlet类。 创建类继承HttpServlet
- 注册Servlet ,让框架能找到Servlet
例子:
1.创建自定义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(); } }- 注册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"); //3.3 过滤器Filterreturn bean; } } 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 @Mapper public interface StudentDao { Student selectById(@Param("stuId") Integer id); }第二种方式 @MapperScan用了@MapperScan,就可以不用写@ Mapper
@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文件的目录
#指定mapper文件的位置 mybatis.mapper-locations=classpath:mapper*.*第四个 事务Spring框架中的事务:
1) 管理事务的对象: 事务管理器(接口, 接口有很多的实现类)
例如:使用Jdbc或mybatis访问数据库,使用的事务管理器:DataSourceTransactionManager
2 ) 声明式事务: 在xml配置文件或者使用注解说明事务控制的内容
控制事务: 隔离级别,传播行为, 超时时间
3)事务处理方式:
1) Spring框架中的[@Transactional ](/Transactional ) 2) aspectj框架可以在xml配置文件中,声明事务控制的内容
SpringBoot中使用事务: 上面的两种方式都可以。
1)在业务方法的上面加入@Transactional , 加入注解后,方法有事务功能了。
2)明确的在 主启动类的上面 ,加入@EnableTransactionManager
例子:
@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; }@SpringBootApplication @EnableTransactionManagement @MapperScan(basePackages = "com.bjpowernode.dao") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }MyBatis生成器- pom.xml中
org.mybatis.generator mybatis-generator-maven-plugin 1.3.6 GeneratorMapper.xml true true org.springframework.boot spring-boot-maven-plugin - GeneratorMapper.xml
- / 和
@Configuration
public class SpringConfig {
@Bean
public Student createStudent(){
Student s1 = new Student();
s1.setName("张三");
s1.setAge(26);
s1.setSex("男");
return s1;
}
@Bean(name = "lisiStudent")
public Student makeStudent(){
Student s2 = new Student();
s2.setName("李四");
s2.setAge(22);
s2.setSex("男");
return s2;
}
}
1.2 @ImporResource


