# springboot-mbyd
**Repository Path**: mbyd/springboot-mbyd
## Basic Information
- **Project Name**: springboot-mbyd
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 0
- **Created**: 2019-05-09
- **Last Updated**: 2023-11-07
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# spring boot 使用
#### 介绍
记录第一次搭框架,遇到好多坑,各种百度。。。
- ### 搭建spring boot框架
1 . pom.xml中添加springboot的依赖
```
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-maven-plugin
```
2 . 添加controller
```
@RestController
public class UserController {
@GetMapping("/hello")("/hello")
public String hello(){
return "hello world";
}
}
```
3 . 添加启动类
```
@SpringBootApplication
public class BootStrap {
public static void main(String[] args) {
SpringApplication.run(BootStrap.class,args);
}
}
```
- ### spring boot + spring-data-jpa
1 . 添加依赖
```
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
8.0.16
```
2 . 创建实体类
```
@Entity
@Table(name = "t_user")
@Data
public class User {
//必须要指定一个@ID 否则会报错 No identifier specified for entity: domain.com.wy.User
@Id
private int id;
private String name;
private int age;
}
```
3 . 创建Repository继承JpaRepository绑定实体类
```
public interface UserRepository extends JpaRepository {
}
```
4 . 在application.properties中添加数据库配置
```
spring.datasource.url=jdbc:mysql://localhost:3306/mytestdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
5 . 在controller中直接注入就可以使用了
```
@Autowired
private UserRepository userRepository;
@GetMapping("/listjpa")
public List findAll(){
return userRepository.findAll();
}
```
- ### jpa 添加分页
1 . 继承PagingAndSortingRepository
```
public interface UserRepository extends PagingAndSortingRepository {
}
```
2 . 添加处理信息
```
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page findByPage(int pageNo, int pageSize){
PageRequest request = this.buildPageRequest(pageNo,pageSize);
Page sourceCodes= this.userRepository.findAll(request);
return sourceCodes;
}
//构建PageRequest
private PageRequest buildPageRequest(int pageNumber, int pagzSize) {
return PageRequest.of(pageNumber - 1, pagzSize);
}
}
```
3 . controller中添加分页信息
@GetMapping("/findbypagejpa")
public org.springframework.data.domain.Page findByPageJpa(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize",defaultValue = "2") int pageSize){
org.springframework.data.domain.Page byPage = userService.findByPage(pageNo, pageSize);
return byPage;
}
- ### spring boot + mybatis
1 . 添加依赖
```
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
mysql
mysql-connector-java
8.0.16
```
2 . 创建mapper
```
public interface UserMapper {
@Select("select * from t_user")
List findAll();
}
```
3 . 在启动类中添加mapper扫描路径
```
@SpringBootApplication
@MapperScan("boottest.mybatisrepo")
public class BootStrap {
public static void main(String[] args) {
SpringApplication.run(BootStrap.class,args);
}
}
```
- ### spring boot + mybatis 添加分页插件
1 . 添加依赖
```
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.10
```
2 . 在mapper添加分页信息
```
@Select("select * from t_user")
Page findByPage();
```
3 . 在调用的时候传入页码信息
```
@GetMapping("/findbypage")
public PageInfo findByPage(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize",defaultValue = "2") int pageSize){
PageHelper.startPage(pageNo, pageSize);
Page byPage = mapper.findByPage();
PageInfo pageInfo = new PageInfo<>(byPage);
return pageInfo;
}
```
- ### 添加 AOP
```
@Aspect
@Component
@Slf4j
public class HttpAspect {
//定义切点
@Pointcut("execution(public * boottest.controller..*(..))")
public void log(){}
@Before("log()")
public void before(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
log.info("url={}", request.getRequestURI());
//method
log.info("method={}", request.getMethod());
//ip
log.info("ip={}", request.getRemoteAddr());
//method
log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//param
log.info("args={}", joinPoint.getArgs());
}
//returning="obj" 将返回结果绑定给参数。returning 和 参数名称必须一致
@AfterReturning(returning = "obj",pointcut = "log()")
public void doAfterReturn(Object obj){
log.info("返回结果----{}",obj);
}
}
```
- ### 使用spring boot 自动配置
1 . XXConfig.java
```
/**
* 配置文件的存放位置有特殊要求!!!有以下三种方式:
* 1.放到application.properties中
* 2.放到application-xxx.properties中,需要在application.properties中激活xxx。spring.profiles.active=xxx
* 3.放到自定义的properties中。需要加上@PropertySource("classpath:application-config.properties")来指定加载路径
*/
@Component
@Data
//@PropertySource("classpath:application-config.properties")
@ConfigurationProperties(prefix = "people")
public class XXConfig {
private String name;
private int age;
}
```
2 . application-xxx.properties
```
people.name=xiaomei
people.age=18
```
3 . application.properties
```
spring.profiles.active=xxx
```
- ### 自定义拦截器
1 . 自定义注解设置拦截路径和忽略的路径,以及触发条件等
```
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Interceptor {
String[] pathPatterns() default {};
String[] excludePatterns() default {};
int order() default 0;
//下面的未实现
Class ignore() default Ignore.class;
/**
* @return 系统配置
*/
String condition() default "";
/**
* 测试处理器
*
* @return ConditionHanlder
*/
Class extends ConditionHanlder> conditionHandler() default DefaultHandler.class;
}
```
2 . 解析注解
```
/**
* 解析注解
* 1.通过实现ApplicationContextAware接口得到applicationContext
* 2.从applicationContext中得到含有Interceptor注解的bean
* 3.实现WebMvcConfigurer接口,根据注解中的参数添加拦截器。
* 4.根据注解中的参数进行拦截器的排序
* 5.如果有ignore参数,自定义拦截器,判断是否需要拦截如果不需要拦截,则放掉。
*/
public class InterceptHanlder implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext context;
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] beanNames = context.getBeanNamesForAnnotation(Interceptor.class);
List interceptors = Arrays.stream(beanNames).map(bean -> context
.getBean(bean, HandlerInterceptorAdapter.class)).sorted((o1, o2) -> {
Interceptor c1 = o1.getClass().getAnnotation(Interceptor.class);
Interceptor c2 = o2.getClass().getAnnotation(Interceptor.class);
return c1.order() - c2.order();
}).collect(Collectors.toList());
interceptors.forEach(interceptor->{
InterceptorRegistration registration = registry.addInterceptor(interceptor);
Interceptor annotation = interceptor.getClass().getAnnotation(Interceptor.class);
registration.addPathPatterns(annotation.pathPatterns());
registration.excludePathPatterns(annotation.excludePatterns());
});
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}
```
3 . 在META-INF中添加spring.factories,实现spring自动配置
```
# Auto Configure 自动配置放到META-INF/spring.factories中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
interceptor.com.wy.InterceptHanlder
```
- ### spring boot + redis
1 . 添加依赖
```
org.springframework.boot
spring-boot-starter-data-redis
```
2 . 在application.properties中添加redis的配置
```
spring.redis.host=127.0.0.1
spring.redis.port=6379
```
3 . 在程序中注入RedisTemplate就可以使用了
```
@Autowired
private RedisTemplate redisTemplate;
public void save(String key,String value){
redisTemplate.boundValueOps(key).set(value);
}
public String get(String key){
return (String) redisTemplate.boundValueOps(key).get();
}
```
4 . 以上是使用spring的配置,还可以自定义配置
4.1 在application.properties中添加属性
```
spring.redis.keyprefix=springboot-test
```
4.2 添加属性配置文件
```
@Data
@ConfigurationProperties("spring.redis")
public class RedisProperties {
private String host;
private int port;
private String keyprefix;
}
```
4.3 添加配置文件
```
@Configuration
@Import(RedisProperties.class)
public class RedisConfig {
@Bean
@ConditionalOnMissingBean
public RedisTemplate