@Value 中的 SpEL 重构(加密属性)

Vít*_*čka 3 java spring spring-security spring-el

我有一个Spring Security配置,我必须在其中使用加密属性。我有实用程序静态方法,PasswordUtil.decode()通过它我可以解码一个属性以供进一步使用。

以下解决方案有效,但特定的SpEL对我来说看起来很丑陋。所以,我的问题是否可以将给定的SpEL表达式重构为更好/更短/惯用的东西?

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("#{T(my.package.PasswordUtil).decode('${signkey.password}')}")
    private String signKeyPassword;

}
Run Code Online (Sandbox Code Playgroud)

dim*_*sli 5

您可以注册自定义 SpEL 解析器函数,如参考文档 中所示。这意味着您可以创建一个自定义 SpEL 关键字,该关键字将在您的自定义代码中解析,也支持输入。

换句话说,您将能够编写而不是:

@Value("#{T(my.package.PasswordUtil).decode('${signkey.password}')}")
private String signKeyPassword;
Run Code Online (Sandbox Code Playgroud)

下面你的自定义 SpEL 关键字是mydecode

@Value("#{ #mydecode( '${signkey.password}' ) }")
String signKeyPassword;
Run Code Online (Sandbox Code Playgroud)

此选项:1) 显着减少 SpEL 字符串文字,2) 让您有机会选择在您的域中有意义的名称 3) 因为它本质上是一个方法调用,它可以在不同的 @Value 中与不同的输入一起使用SpEL 注射。

下面是一个工作示例。请注意,它不是特定于 Spring Security(不使用它)也不是特定于 Spring Boot(使用它):

POM 文件

Spring Initializr自动生成这个没有添加任何组件。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
Run Code Online (Sandbox Code Playgroud)

主类DemoApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;


@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

    SecurityConfiguration securityConfiguration = SpringApplication.run(DemoApplication.class, args).getBean(SecurityConfiguration.class);

        System.out.println(securityConfiguration.getSignKeyPassword());
    }

    @Bean
    MyCustomSpELFunctionRegister customSpelFunctionProvider() {
        return new MyCustomSpELFunctionRegister();
    }
}
Run Code Online (Sandbox Code Playgroud)

安全配置:

正如前面提到的 Spring Security 不可知论者。它使用自定义 SpEL 关键字解析器。

package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SecurityConfiguration {

    @Value("#{ #mydecode( '${signkey.password}' ) }")
    String signKeyPassword;

    public String getSignKeyPassword() {
        return signKeyPassword;
    }
}
Run Code Online (Sandbox Code Playgroud)

MyCustomSpELDecoderFunction

这是您将隐藏执行工作的 Utils 静态方法的类

package com.example.demo;

public abstract class MyCustomSpELDecoderFunction {

    //needs to be public
    //alternative use interface with defined static method
    public static String mydecode(String encrypted) {
        return "myutils decrypt";
    }
}
Run Code Online (Sandbox Code Playgroud)

MyCustomSpELFunctionRegister 类

这是将自定义 SpEL 关键字连接到 Utils 类的粘合代码。它实现 BeanFactoryPostProcessor 以在创建任何 bean 之前执行注册,从而停止 @Value 注入。

package com.example.demo;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MyCustomSpELFunctionRegister implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver() {
            @Override
            protected void customizeEvaluationContext(StandardEvaluationContext standardEvaluationContext) {
                try {

                    //here we register all functions
                    standardEvaluationContext.registerFunction("mydecode", MyCustomSpELDecoderFunction.class.getMethod("mydecode", new Class[] { String.class }));

                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)