spring boot 简明手册

364 阅读2分钟

application.yml常用配置

spring:
  profiles:
    active: dev,female
  datasource:
    url: jdbc:mysql://192.168.56.101:3306/dev
    type: com.zaxxer.hikari.HikariDataSource
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  redis:
    database: 0
    host: 192.168.56.101
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: -1
        min-idle: 0
    password: ''
    port: 6379
    timeout: 5000

server:
  port: 8083
  compression:
    enabled: true


logging:
  file:
    path: E:/java/demo/log

site:
  meta: this is a meta
  title: ${site.meta}
  keywords: this is a keywords

自定义配置

写入配置 src\main\resources\application.properties

info.site.url=http://www.wkcto. com
info.site.tel-010-68686868

读取自定义到配置类的方式有两种

@Value注解

用于逐个读取自定义的配置,比如:

@Value("${wkcto.site}")private string site;
@value("${wkcto.tel}")private string tel;

@Configuration导入注解

@Component
@ConfigurationProperties(prefix="info.site")
public class siteConfig {
    private String url;
    private String tel;

    public String geturl() {
        return url;
    }

    public void seturl(String url) {
        this.url = url;
    }
}

参数传入

请求参数

?id=123

    @GetMapping("/check")
    public ResponseEntity<CodeMessage> check(@RequestParam(value="id",required=false,defaultValue="") Long id){
       ...
    }

路径参数

	@PostMapping("/enable/{id}")
    public ResponseEntity<CodeMessage> enable(@PathVariable(value="id") String id){
        ...
    }

校验器

# 校验器
## 验证和隐藏属性
1.创建entity
``` java
@AllArgsConstructor
@Getter
@Setter
public class User {
    public interface UserSimpleView {};
    public interface UserDetailView extends UserSimpleView {};

    @JsonView(UserSimpleView.class)
    private long id;

    @JsonView(UserSimpleView.class)
    private String username;

    @JsonView(UserDetailView.class)
    private String password;
}

2.根据UserSimpleView或UserDetailView隐藏属性

@RestController
public class TestController {
    @GetMapping("/test")
    @JsonView(User.UserSimpleView.class)
    public ArrayList<User> test(@PageableDefault(size = 10,page = 0,sort = "username,desc") Pageable pageable){
        System.out.println();
        ArrayList<User> users = new ArrayList<>();
        users.add(new User(1,"hello","123456"));
        users.add(new User(2,"hello1","123456"));
        users.add(new User(3,"hello2","123456"));

        return users;
    }
    @GetMapping("/test2")
    @JsonView(User.UserDetailView.class)
    public ArrayList<User> test2(@PageableDefault(size = 10,page = 0,sort = "username,desc") Pageable pageable){
        System.out.println();
        ArrayList<User> users = new ArrayList<>();
        users.add(new User(1,"hello","123456"));
        users.add(new User(2,"hello1","123456"));
        users.add(new User(3,"hello2","123456"));

        return users;
    }
}

自定义校验器

1.新建注解

@Target({ElementType.METHOD, ElementType.FIELD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ShiwusuoExistValidator.class)
public @interface ShiwusuoExist {
    String message();

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

2.实现注解类

public class ShiwusuoExistValidator implements ConstraintValidator<ShiwusuoExist, Object> {
    @Autowired
    private ShiwusuoService shiwusuoService;

    @Override
    public void initialize(ShiwusuoExist constraintAnnotation) {

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Shiwusuo shiwusuo = shiwusuoService.getById((Long) value);
        if(shiwusuo==null){
            return false;
        }else{
            //传递查询到的对象
            RequestContextHolder.getRequestAttributes().setAttribute(
                    "shiwusuo", shiwusuo, RequestAttributes.SCOPE_REQUEST
            );
            return true;
        }
    }
}

3.添加到model

public class User {
	
	@MyConstraint(message = "这是一个测试")
	private String username;
}

或者

 public ResponseEntity<CodeMessage> update(@ShiwusuoExist(message = "指定的id不存在") Long id){
		
        //接收传递过来的查询到的对象
        Shiwusuo shiwusuo2 = (Shiwusuo) RequestContextHolder.getRequestAttributes().getAttribute(
                "shiwusuo",
                RequestAttributes.SCOPE_REQUEST
        );
 }

切片拦截

filter方式

filter方式缺点 不能获取控制器信息

@Component方式注册

@Component
public class TimeFilter implements Filter {

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		System.out.println("time filter destroy");
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("time filter start");
		long start = new Date().getTime();
		chain.doFilter(request, response);
		System.out.println("time filter 耗时:"+ (new Date().getTime() - start));
		System.out.println("time filter finish");
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("time filter init");
	}

}

配置类WebMvcConfigurerAdapter方式注册

如果不用@component可以使用如下方式注册

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
	
	@Bean
	public FilterRegistrationBean timeFilter() {
		
		FilterRegistrationBean registrationBean = new FilterRegistrationBean();
		
		TimeFilter timeFilter = new TimeFilter();
		registrationBean.setFilter(timeFilter);
		
		List<String> urls = new ArrayList<>();
		urls.add("/*");
		registrationBean.setUrlPatterns(urls);
		
		return registrationBean;
		
	}

}

interceptor方式

interceptor缺点 不能获得参数

创建Interceptor

@Component
public class TimeInterceptor implements HandlerInterceptor {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("preHandle");
		
		System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
		System.out.println(((HandlerMethod)handler).getMethod().getName());
		
		request.setAttribute("startTime", new Date().getTime());
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle");
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));

	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion");
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));
		System.out.println("ex is "+ex);

	}

}

注册 Interceptor

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
	
	@Autowired
	private TimeInterceptor timeInterceptor;
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(timeInterceptor);
	}
}

aspect方式

统一异常处理

  1. 创建一个异常类
public class UserNotExistException extends RuntimeException {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6112780192479692859L;
	
	private String id;
	
	public UserNotExistException(String id) {
		super("user not exist");
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}
  1. 创建异常类处理类
@ControllerAdvice
public class ControllerExceptionHandler {
	
	@ExceptionHandler(UserNotExistException.class) //这里写入需要处理的异常类
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Map<String, Object> handleUserNotExistException(UserNotExistException ex) {
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}

}
  1. 抛出异常
@RestController
@RequestMapping("/user")
public class UserController {

        @GetMapping("/{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	public User getInfo(@PathVariable String id) {
		
		throw new UserNotExistException(id);

	}
}

swagger

juejin.cn/post/684490…

security

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity HttpSecurity) throws Exception {
        HttpSecurity.formLogin()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }
}
@Slf4j
@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录用户名:" + username);
        String password = passwordEncoder.encode("123456");
        log.info("数据库密码是:"+password);
        return new User(username, password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}