【问题标题】:Cannot access application.properties property in AttributeConverter implementation无法访问 AttributeConverter 实现中的 application.properties 属性
【发布时间】:2022-01-20 19:10:59
【问题描述】:

我正在尝试访问存储在 application.properties 中的加密密钥,并将其设置为我的 AttributeEncryptor 中的 SECRET 属性。

这是课程:

package com.nimesia.sweetvillas.encryptors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import javax.persistence.AttributeConverter;
import java.security.InvalidKeyException;
import java.security.Key;
import java.util.Base64;

@Component
public class AttributeEncryptor implements AttributeConverter<String, String> {

    private static final String AES = "AES";
    @Value("${datasource.encryptkey}")
    private String SECRET;

    private final Key key;
    private final Cipher cipher;

    public AttributeEncryptor() throws Exception {
        key = new SecretKeySpec(SECRET.getBytes(), AES);
        cipher = Cipher.getInstance(AES);
    }

    @Override
    public String convertToDatabaseColumn(String attribute) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return Base64.getEncoder().encodeToString(cipher.doFinal(attribute.getBytes()));
        } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(Base64.getDecoder().decode(dbData)));
        } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            throw new IllegalStateException(e);
        }
    }
}

datasource.encryptkey 在 application.properties 中。 我试图从控制器访问它并且它有效。但是当我在这里尝试使用它时,它给了我一个 NullPointerException。

希望我很清楚。 提前致谢

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    类是在设置属性之前创建的!

    您应该将其添加到构造函数中:

    private final String SECRET;
    
    private final Key key;
    private final Cipher cipher;
    
    public AttributeEncryptor(@Value("${datasource.encryptkey}") String secret) throws Exception {
        SECRET = secret;
        key = new SecretKeySpec(SECRET.getBytes(), AES);
        cipher = Cipher.getInstance(AES);
    
    }
    

    【讨论】:

    • 谢谢伙计。你是我的救星
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2014-09-19
    • 2020-03-18
    • 2023-03-07
    • 2019-05-06
    • 2016-06-05
    • 2013-05-20
    相关资源
    最近更新 更多