SpringBoot配置类集合

一、消息转换器

1.WebMvcConfigurationSupport

JacksonObjectMapper类–>自定义序列化器


/**
 * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
 * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
 */
public class JacksonObjectMapper extends ObjectMapper {
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    public JacksonObjectMapper() {
        super();
        //收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);

        //反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


        SimpleModule simpleModule = new SimpleModule()
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
                .addSerializer(BigInteger.class, ToStringSerializer.instance)
                .addSerializer(Long.class, ToStringSerializer.instance)
                .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        //注册功能模块 例如,可以添加自定义序列化器和反序列化器
        this.registerModule(simpleModule);
    }
}

将对象JacksonObjectMapper添加到消息转换器中,配置如下:

@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override//设置静态资源映射
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("资管映射开始.........");
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");

    }
    @Override//扩展mvc框架的消息转换器
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器......");
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器,底层使用Jackson将java对象转换成json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器追加到mvc框架的转换器集合中,索引0代表优先使用我们自己的转换器
        converters.add(0,messageConverter);
    }
}

2.WebMvcConfigurer

    @Bean//使用@Bean注入fastJsonHttpMessageConvert
    public HttpMessageConverter fastJsonHttpMessageConverters() {
        //1.需要定义一个Convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        SerializeConfig.globalInstance.put(Long.class, ToStringSerializer.instance);

        fastJsonConfig.setSerializeConfig(SerializeConfig.globalInstance);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastConverter;
        return converter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(fastJsonHttpMessageConverters());
    }
}

二、MbatisPlusConfig配置

它是是一系列的实现InnerInterceptor的拦截器链,也可以理解为一个集合

  • 自动分页: PaginationInnerInterceptor分页插件(最常用)
  • 乐观锁:OptimisticLockerInnerInterceptor

配置如下:

//配置MP的分页插件
@Configuration //配置类让程序扫到它
@Slf4j
public class MybatisPlusConfig {
    @Bean//要spring来管理他
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        log.info("分页功能开启。。。。");
        MybatisPlusInterceptor mpi = new MybatisPlusInterceptor();
        //添加分页拦截器
        mpi.addInnerInterceptor(new PaginationInnerInterceptor());
       //添加乐观锁拦截器
        mpi.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mpi;
    }
}

分页查询使用方法

在controller中编写,如下例子:

@GetMapping("/page")//分页查询
    public R<Page> page(int page, int pageSize){
        //构造分页构造器
        Page<Category> p1 = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //添加排序条件
        lqw.orderByAsc(Category::getSort);
        //执行查询
        categoryService.page(p1,lqw);
        return R.success(p1);
    }

三、application.yml配置文件

server:
  port: 8080
spring:
  application:
    name: reggie_take_out #应用名称
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: root
  main:
    banner-mode: off #Springboot启动的图案
mybatis-plus:
  configuration:
    # address_book---->AddressBook
    #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
    map-underscore-to-camel-case: true
    # 开启mybatisplus日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID
    banner: false
reggie_filePath: #配置上传文件的路径
  path: D:\

四、RedisConfig配置

/*
 * redis配置类
 * */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
        //默认的key序列化器为:JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory (connectionFactory);
        return redisTemplate;

    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 中,可以使用 `@ConfigurationProperties` 注解来读取配置文件。当配置文件中有一个以特定前缀开头的配置集合时,可以使用 `@ConfigurationProperties` 注解与 `@Bean` 注解结合使用来读取。 例如,假设我们有一个配置文件 `application.properties`,其中包含以下配置项: ``` myapp.items[0].name=apple myapp.items[0].price=5 myapp.items[1].name=banana myapp.items[1].price=3 ``` 我们可以通过以下方式读取该配置集合: 首先,我们需要创建一个 Java 来表示每个配置项的属性。例如,我们可以创建一个 `Item` : ```java public class Item { private String name; private int price; // 省略 getter 和 setter 方法 } ``` 然后,我们可以创建一个 `ItemsConfiguration` 来读取配置集合: ```java @Configuration @ConfigurationProperties(prefix = "myapp") public class ItemsConfiguration { private List<Item> items = new ArrayList<>(); public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } @Bean public List<Item> itemList() { return items; } } ``` 在上面的代码中,我们使用 `@ConfigurationProperties` 注解来指定配置项的前缀为 `myapp`,并且定义了一个 `List<Item>` 型的属性 `items` 来保存配置集合。我们还定义了一个 `itemList()` 方法,用于将 `items` 属性作为 Bean 注册到 Spring 容器中。 最后,在需要使用该配置集合的地方,我们可以使用 `@Autowired` 注解来注入 `List<Item>` 型的 Bean: ```java @RestController public class MyController { @Autowired private List<Item> items; @GetMapping("/items") public List<Item> getItems() { return items; } } ``` 这样就可以通过访问 `/items` 接口来获取配置集合了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝朽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值