java - Spring @Value 字段为空

标签 java spring hibernate spring-mvc

我在 Spring 中遇到 @Value 注释问题,我正在尝试从属性文件中设置字段。我的配置applicationContext.xml是

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="locations">
        <list>
            <value>classpath:config/local/*.properties</value>
        </list>
    </property>
</bean>

属性文件位于 src/main/resources/config/local/general.properties

一般属性

general.key="EDC183ADVARTT"

在我的类(class)中,我想从该文件注入(inject)字段。 我的类(class)

import java.security.Key;

import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec;
import javax.persistence.AttributeConverter;

import org.postgresql.util.Base64; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;

@javax.persistence.Converter 
@Component 
public class EntityEncryptionConverter implements AttributeConverter<String, String> {

    @Value("${general.key}")
    private String keyCode;

    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final byte[] KEY = "395DEADE4D23DD92".getBytes();

    public String convertToDatabaseColumn(String ccNumber) {
        System.out.print(keyCode);
        // do some encryption
        Key key = new SecretKeySpec(KEY, "AES");
        try {
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            return Base64.encodeBytes(c.doFinal(ccNumber.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String convertToEntityAttribute(String dbData) {
        // do some decryption
        Key key = new SecretKeySpec(KEY, "AES");
        try {
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            return new String(c.doFinal(Base64.decode(dbData)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

为什么我的 KeyCode 值为空?

最佳答案

这个:

<value>classpath:config/local/*.properties</value>

应该是:

 <value>classpath:*.properties</value>

关于java - Spring @Value 字段为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504150/

相关文章:

Java 线程 : Specifying what should be executed in the run function

java - 为什么 invokevirtual 的目标类型从 javac target 1.1 更改为 1.2?

java - 有没有办法处理 Spring 中自定义异常处理程序内部抛出的异常?

java - 在 Eclipse IDE for Java Developers 中安装 STS 时显示错误

java - Hibernate 不自动创建表

java - 我可以改进 XWiki 搜索结果以包含关键字匹配吗?

java - 从4.3.11.Final版本切换到5.0.1.Final导致编译报错

java - 如何将 Hibernate 缓存中的项目保留至少 24 小时?

java - 图与关系数据库的性能

java - EclipseLink:默认情况下不获取某些字段