Spring Boot笔记

环境:jdk1.8 、spring boot 2.0、idea


  • @SpringBootApplication
    标注在类上,表示这个类是一个SpringBoot应用

  • @SpringBootConfiguration
    标注在类上,表示这个SpringBoot的配置类,相当于xml配置文件

  • @Configuration
    标注在类上,表示这个类是Spring的配置类

  • @EnableAutoConfiguration
    开启自动配置功能,SpringBoot会自动完成许多配置,简化了以前的繁琐的配置

  • @ComponentScan
    标注在类上,指定要扫描的包,默认只扫描主程序类所在的包及其子包


YAML语法

  • 字面量:单个值
  • 对象:键值对
  • 数组:一组数据的集合

字面量

number: 25
str: 'hello world'
flag: true

对象,也称为Map映射,包含属性和值

#对象,也称为Map映射,包含属性和值
# 写法1:换行写,使用缩进
user:
name: zhaoYoung
age: 23
# 写法2:行内写法
user: {name: zhaoYoung,age: 23}

数组,如List、Set等

# 写法1:换行写,使用短横线
names:
­ tom
­ jack
­ alice
# 写法2:行内写法
names: [tom,jack,alice]

多环境配置

YAML

Spring Boot笔记_第1张图片

properties配置文件也一样


加载外部属性文件

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
// 加入容器
@Component
// 加载外部属性文件
@PropertySource({"classpath:user.properties"})
// 默认读取全局配置文件获取值,将当前类的所有属性与配置文件中的user绑定
@ConfigurationProperties(prefix = "user")
public class User implements Serializable{

    private static final long serialVersionUID = 2503950912022065409L;

    private String userName;

    private Integer age;

    private Date birthday;

    private List lists;

    private Map maps;

    private Address address;

    // get set方法

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", lists=" + lists +
                ", maps=" + maps +
                ", address=" + address +
                '}';
    }
}

Spring Boot笔记_第2张图片


热启动

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
        dependency>

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <fork>truefork>
                configuration>
            plugin>
        plugins>
    build>

静态资源

查看源码,可知道默认的静态资源文件位置如下

@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties implements ResourceLoaderAware {
    private static final String[] SERVLET_RESOURCE_LOCATIONS = new String[]{"/"};
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", 
    "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private static final String[] RESOURCE_LOCATIONS;
    private String[] staticLocations;
    private Integer cachePeriod;
    private boolean addMappings;
    private final ResourceProperties.Chain chain;
    private ResourceLoader resourceLoader;

如不手动指定静态资源,则可直接访问以上默认路径下的静态资源,如:http://localhost:8888/css/style.css

如需手动配置,可以在配置文件中自己去指定静态资源位置

#指定静态资源的位置
spring.resources.static-locations=classpath:/mybatis/

demo:如我想访问mybatis目录下的mybatis-config.xml文件,则访问http://localhost:8888/mybatis-config.xml即可
Spring Boot笔记_第3张图片


拦截器

@Configuration
public class CustomMvcConfig implements WebMvcConfigurer {

    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加指定拦截器 需要拦截的路径 除了哪些路径
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/");
    }
}
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor.preHandle");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor.afterCompletion");
    }
}

指定异常跳转页面

默认会去读取templates/error/目录下的html文件,html文件默认以具体的错误码(如404.html)为文件名,或模糊匹配如4xx.html、5xx.html


注册Servlet三大组件

@Configuration
public class CustomServletConfig {

    // 注册Servlet
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean registrationBean=new ServletRegistrationBean();
        registrationBean.setServlet(new MyServlet());
        registrationBean.addUrlMappings("/myServlet");
        return registrationBean;
    }

    // 注册Filter
    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new MyFilter());
        registrationBean.addUrlPatterns("/test1","/test2");
        return registrationBean;
    }

    // 注册Listener
    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean<>();
        registrationBean.setListener(new MyListener());
        return registrationBean;
    }

}
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("MyServlet.doGet");
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("MyServlet.doPost");
    }
}
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter.init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
    FilterChain filterChain) throws IOException, ServletException {
        System.out.println("MyFilter.doFilter");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("MyFilter.destroy");
    }
}
public class MyListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("MyListener.contextInitialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("MyListener.contextDestroyed");
    }
}

分页插件pageHelper

maven依赖

        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelper-spring-boot-starterartifactId>
            <version>1.2.3version>
        dependency>

java代码

    public PageInfo fingByPage(int pageNum,int pageSize){
        // 设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        // 数据库查询
        List allProvince = cityMapper.getAllProvince();
        // 整合分页插件
        PageInfo pageInfo = new PageInfo<>(allProvince);
        return pageInfo;
    }

你可能感兴趣的:(spring,boot)