2 Star 1 Fork 0

zhrun8899 / learning-notes

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
springboot-bean策略.md 2.48 KB
一键复制 编辑 原始数据 按行查看 历史
zhrun8899 提交于 2019-04-04 08:54 . 20190404

按条件生成Bean

1.根据环境生成

 @Bean
    @Profile({ "dev", "test" }) // 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {

​    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
​    performanceInterceptor.setMaxTime(120000);
​    performanceInterceptor.setFormat(true);
​    return performanceInterceptor;
}

2.根据properties生成

3.根据class及bean生成

  •  @Configuration("defaultFastjsonConfig")
     @ConditionalOnClass(com.alibaba.fastjson.JSON.class)
     @ConditionalOnMissingBean(FastJsonHttpMessageConverter.class)
     @ConditionalOnWebApplication
     public class DefaultFastjsonConfig {
     
     @Bean
     public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
         FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
         converter.setFastJsonConfig(fastjsonConfig());
         converter.setSupportedMediaTypes(getSupportedMediaType());
         return converter;
     }
     
     ​         /**
     
     ​        **    fastjson的配置
     ​         */
     public FastJsonConfig fastjsonConfig() {
     FastJsonConfig fastJsonConfig = new FastJsonConfig();
     fastJsonConfig.setSerializerFeatures(
     ​        SerializerFeature.PrettyFormat,
     ​        SerializerFeature.WriteMapNullValue,
     ​        SerializerFeature.WriteEnumUsingToString
     );
     fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
     ValueFilter valueFilter = new ValueFilter() {
     ​    public Object process(Object o, String s, Object o1) {
     ​        if (null == o1) {
     ​            o1 = "";
     ​        }
     ​        return o1;
     ​    }
     };
     fastJsonConfig.setCharset(Charset.forName("utf-8"));
     fastJsonConfig.setSerializeFilters(valueFilter);
     
     //解决Long转json精度丢失的问题
     SerializeConfig serializeConfig = SerializeConfig.globalInstance;
     serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
     serializeConfig.put(Long.class, ToStringSerializer.instance);
     serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
     fastJsonConfig.setSerializeConfig(serializeConfig);
     return fastJsonConfig;
     }
     
     /**
     
     - 支持的mediaType类型
       */
       public List<MediaType> getSupportedMediaType() {
       ArrayList<MediaType> mediaTypes = new ArrayList<>();
       mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
       return mediaTypes;
       }
1
https://gitee.com/zhrun8899/learning-notes.git
git@gitee.com:zhrun8899/learning-notes.git
zhrun8899
learning-notes
learning-notes
master

搜索帮助