环境: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
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<String> lists;
private Map<String,Object> maps;
private Address address;
// get set方法
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", age=" + age +
", birthday=" + birthday +
", lists=" + lists +
", maps=" + maps +
", address=" + address +
'}';
}
}
热启动
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork><!-- 如果没有该项配置,devtools不会起作用,即应用不会restart -->
</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即可
拦截器
@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<MyServlet> registrationBean=new ServletRegistrationBean();
registrationBean.setServlet(new MyServlet());
registrationBean.addUrlMappings("/myServlet");
return registrationBean;
}
// 注册Filter
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyFilter());
registrationBean.addUrlPatterns("/test1","/test2");
return registrationBean;
}
// 注册Listener
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> 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.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
java代码
public PageInfo<City> fingByPage(int pageNum,int pageSize){
// 设置分页参数
PageHelper.startPage(pageNum,pageSize);
// 数据库查询
List<City> allProvince = cityMapper.getAllProvince();
// 整合分页插件
PageInfo<City> pageInfo = new PageInfo<>(allProvince);
return pageInfo;
}