SpringBoot+讀取properties文件內容並注入到類屬性中


第一種方法,以發送短信功能為例:

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}")

 

完整代碼:

import java.util.HashMap;
import java.util.Map;

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

import com.atguigu.scw.vo.resp.AppResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SmsTemplate {
    
    @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()));
            return AppResponse.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注解也行

 

 

配置文件的代碼:

package com.atguigu.scw.project.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import com.atguigu.scw.project.component.OssTemplate;

@SpringBootConfiguration
public class AppProjectConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "oss")
    public OssTemplate ossTemplate() {
        return new OssTemplate();
    }

}

 

上傳文件的代碼:

import java.io.InputStream;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@ToString
@Data
@Slf4j
//@Component
public class OssTemplate {
//    @Value("${oss.endpoint}")
    String endpoint;
    // 雲賬號AccessKey有所有API訪問權限
    String accessKeyId;
    String accessKeySecret;
    String bucket;

    public String 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 = new OSSClientBuilder().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);
            return filepath;
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("文件上傳失敗-{}", tempFileName);
            return null;
        }

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM