1. 程式人生 > >如何解決@Autowired annotation is not supported on static fields問題給靜態變數賦值

如何解決@Autowired annotation is not supported on static fields問題給靜態變數賦值

問題由來: springboot專案中使用加解密功能,金鑰在application.properties檔案中配置,因此加解密服務類需要讀取該變數,為了提高效率,加解密服務類靜態初始化的時候就生成了SecretKeySpec(不是每次呼叫加密或者解密方法時再生成SecretKeySpec)。 如果我們使用如下方式讀取配置檔案,然後賦值給mySecretKey, springboot就會報@Autowired annotation is not supported on static fields

public class EnDecryptionServiceImpl implements IEnDecryptionService
{ @Value("${mySecretKey}") private static String mySecretKey; ... static { try { byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; ivspec = new IvParameterSpec(iv); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ... 這裡用到了mySecretKey。 因此必須把mySecretKey設定為static
} catch (NoSuchPaddingException ex) { log.error("no PKCS5Padding in the jvm", ex); } catch (NoSuchAlgorithmException ex) { log.error("no AES algorithm in the jvm", ex); } catch (Exception ex) { log.error("generic exception"
, ex); } } ...

問題表現: 程式日誌提示@Autowired annotation is not supported on static fields, 並且原先讀取到的mySecretKey為null。

解決方法: 給EnDecryptionServiceImpl 增加一個setMySecretKey,然後在該set方法上面加@Autowired即可。 注意:因為我的setMySecretKey(String secretKey)需要一個字串bean, 因此額外新增一個config生成一個String bean。

    @Autowired
    public void setMySecretKey(String secretKey) {
        mySecretKey = secretKey;
        log.info("set mySecretKey={}", mySecretKey);
        init();
    }

生成String bean

@Configuration
@Slf4j
public class MySecretConfig {
    @Value("${mySecretKey:defatulValue}")
    private  String mySecretKey;

    @Bean
    public String getMySecretKeyFromCfg() {
        return mySecretKey;
    }
}

通過日誌可以發現,EnDecryptionServiceImpl 類的靜態變數mySecretKey已經順利獲取到application.properteis中的值了。

完整的程式碼在[這裡](https://github.com/yqbjtu/springboot/tree/master/CLRDemo)。您只需要關注EnDecryptionServiceImpl 類的靜態變數如何被賦值的,其餘的只是springboot為了演示效果而寫的完整程式的程式碼。