SpringBoot+读取properties文件内容并注入到类属性中

摘要:
tempFileName=UUID.randomUUID().toString().replace("-","")+"_"+fileName;o

第一种方法,以发送短信功能为例:

1.application.properties文件:

sms.host=http://dingxin.market.alicloudapi.com
sms.path=/dx/sendSms
sms.method=POST
sms.appcode=xxxxxxx

2.需要注入的类,在类的上面加上@Component,在类属性上加上@Value("${sms.host}")

SpringBoot+读取properties文件内容并注入到类属性中第1张

完整代码:

importjava.util.HashMap;
importjava.util.Map;

importorg.apache.http.HttpResponse;
importorg.apache.http.util.EntityUtils;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.stereotype.Component;

importcom.atguigu.scw.vo.resp.AppResponse;

importlombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public classSmsTemplate {
    
    @Value("${sms.host}")
    String host ;
    
    @Value("${sms.path}")
    String path ;
    
    @Value("${sms.method}")
    String method ;
    
    @Value("${sms.appcode}")
    String appcode ;
    
    public AppResponse<String> smsSent(Map<String, String>querys) {

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE xxxxxxx
        headers.put("Authorization", "APPCODE " +appcode);

        Map<String, String> bodys = new HashMap<String, String>();


        try{

            HttpResponse response =HttpUtils.doPost(host, path, method, headers, querys, bodys);
            log.debug("短信发送结果-----------:{}",EntityUtils.toString(response.getEntity()));
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            returnAppResponse.ok(response.toString());
        } catch(Exception e) {
            e.printStackTrace();
            return AppResponse.fail(null);
        }
        
    }

}

第二种方法,以上传文件功能为例:

1.application.properties文件:

#单个文件大小
spring.servlet.multipart.max-file-size=10MB
#总文件大小
spring.servlet.multipart.max-request-size=10MB

oss.endpoint=oss-cn-beijing.aliyuncs.com
oss.accessKeyId=xxxxxxx
oss.accessKeySecret=xxxxxxx
oss.bucket=xxxxxx

2.在类上加上@SpringBootConfiguration,把类设置为springboot的配置类,在方法上面加上@Bean和@ConfigurationProperties(prefix = "oss"),赋值后注入到springboot框架,并把类的对象返回

注意:类要加上get和set方法,用lombok的@data注解也行

SpringBoot+读取properties文件内容并注入到类属性中第2张

配置文件的代码:

packagecom.atguigu.scw.project.config;

importorg.springframework.boot.SpringBootConfiguration;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.context.annotation.Bean;

importcom.atguigu.scw.project.component.OssTemplate;

@SpringBootConfiguration
public classAppProjectConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "oss")
    publicOssTemplate ossTemplate() {
        return newOssTemplate();
    }

}

上传文件的代码:

importjava.io.InputStream;
importjava.util.UUID;

importorg.springframework.stereotype.Component;

importcom.aliyun.oss.OSS;
importcom.aliyun.oss.OSSClientBuilder;

importlombok.Data;
importlombok.ToString;
importlombok.extern.slf4j.Slf4j;

@ToString
@Data
@Slf4j
//@Component
public classOssTemplate {
//@Value("${oss.endpoint}")
String endpoint;
    //云账号AccessKey有所有API访问权限
String accessKeyId;
    String accessKeySecret;
    String bucket;

    publicString upload(String fileName, InputStream inputStream) {

        log.debug("endpoint={}", endpoint);
        log.debug("accessKeyId={}", accessKeyId);
        log.debug("accessKeySecret={}", accessKeySecret);
        log.debug("bucket={}", bucket);
        String tempFileName = null;

        try{

            //创建OSSClient实例。
            OSS ossClient = newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //上传文件流。
            tempFileName = UUID.randomUUID().toString().replace("-", "") + "_" +fileName;
            ossClient.putObject(bucket, "pic/" +tempFileName, inputStream);

            //关闭OSSClient。
ossClient.shutdown();

            // https://bucket.oss-cn-beijing.aliyuncs.com/pic/test.jpg
            String filepath = "https://" + bucket + "." + endpoint + "/pic/" +tempFileName;
            log.debug("文件上传后的路径:{}",filepath);
            returnfilepath;
        } catch(Exception e) {
            e.printStackTrace();
            log.debug("文件上传失败-{}", tempFileName);
            return null;
        }

    }
}

免责声明:文章转载自《SpringBoot+读取properties文件内容并注入到类属性中》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Tomcat设置虚拟目录的方法scp 将数据从一台linux服务器复制到另一台linux服务器下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

android 蓝牙通信编程讲解

以下是开发中的几个关键步骤: 1,首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket,获取输入输出流 4,读取和写入数据 5,断开连接关闭蓝牙 下面是一个demo 效果图: SearchDeviceActivity.java [java]view plaincopy package com.hello.project;      impo...

Scala从入门到精通之四-映射和元组

在Scala中映射之键值对的集合,元组是n个对象的聚集,但是对象的类型不一定相同 本节内容要点   Scala中映射的创建,遍历和查询   如何从可变和不可变映射中做出选择   Scala映射和Java映射见的互操作   Scala中元组的使用 一.构造映射 我们可以这样来构造一个映射: val scores = Map("ysl"->100,"...

java中对list集合中的数据按照某一个属性进行分组

import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; p...

不安装office的情况下如何实现对excel的导入导出

答: 方法一、对于07/10及以后的版本,可以采用openxml sdk,因为07/10都是open xml标准的,利用open xml sdk可以不用安装office而对office文件进行操作。而且速度快。 若03不安装office,可以使用NPOI 。 可以考虑将数据发送到服务端,从服务端生成excel文件,然后再传输会客户端。这样客户端就不需要安装...

C# JSON使用的常用技巧(二)

JSON在php里一句json_encode就可以得到 在C#里我们同样也很容易的可以得到 用到的类库:Newtonsoft.Json.dll 实体类: class Cat { public string A { get; set; } public string B { get; set; } } 通过 JsonConvert:SerializeObj...

Java 设计模式--策略模式,枚举+工厂方法实现

项目中的一个页面跳转功能存在10个以上的if else判断,想要做一下整改 一、什么是策略模式 策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理,最终可以实现解决多重If判断问题。 1.环境(Context)角色:持有一个Strategy的引用。 2.抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象...