昨天在使用@value注解給靜態變量賦值的時候,發現靜態變量的值始終是null。后來搜索一下得知其中原因,spring boot 不允許/不支持把值注入到靜態變量中。但是我們可以變通一下解決這個問題。因為spring boot 支持set方法注入,我們可以利用非靜態set方法注入靜態變量。廢話不多說,貼上我昨天寫的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
@component public class coverimageutil { private static string endpoint; private static string bucketname; @value ( "${oss.endpoint}" ) private void setendpoint(string name){ endpoint = name; } @value ( "${oss.bucketname}" ) private void setbucketname(string name){ bucketname = name; } public static string getimage(string path){ if (stringutils.isempty(path)){ return null ; } // xxx的圖片地址 https://oss.xxx.com/uploads/8f/70/8f70879210f08aaa6f4a04a3d42f3704.jpg if (path.contains( "oss.xxx.com" )){ return path; } string[] str = path.split( "," ); // mt的圖片地址 // key = customer/coverimg/1002,fafa5efeaf3cbe3b23b2748d13e629a1,418530,image/jpeg // url = https://m-t-tesing.oss-cn-hangzhou.aliyuncs.com/customer/coverimg/1002 stringbuilder url = new stringbuilder( "https://" ); url.append(bucketname) .append( "." ) .append(endpoint) .append( "/" ) .append(str[ 0 ]); return url.tostring(); } } |
注意
- 代碼中需要@component注解
- set方法要是非靜態的
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.ydstudio.net/archives/73.html?