我在之前的帖子中问过这个问题:SpEL for spring security: Passing Values from XML to Java based SpEL configuration .但还没有解决。我想从 xml 配置或从外部文件注入(inject)值到 @PreAuthorize(...)
注释中。不像使用@Value
注解注入(inject)那么容易。
为了记忆这个问题,我提供以下信息。
我有以下 xml 配置文件 (example.xml) 具有属性并初始化其相应的值。
<beans> <bean id="userBean" class="x.y.User"> <property name="name" value="A"/> <property name="userId" value="33"/> <bean id="customerBean" class="x.y.Customer"> <property name="name" value="B"/> <property name="customerId" value="33"/> </bean> </beans>
我有以下外部属性文件 (example.properties) 在/WEB-INF 文件夹中。这个文件是一个 上述 XML 配置文件的替代方案。
user.id = 33 customer.id =33
我的 applicationContext.xml 文件中有属性策略持有者配置
<context:property-placeholder location="/WEB-INF/*.properties" ignore-unresolvable="true" /> <bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/example.properties" p:ignoreUnresolvablePlaceholders="true" />
我有两个模型类:
User
和Customer
public class User { private int userId; public int getUserId() { return userId; } } public class Customer { private int customerId; public int getCustomerId(){ return customerId; } }
我有另一个我想限制的服务/ Controller 类 使用
@PreAuthorize
注释的'edit'
方法。限制条件
:方法允许(授权执行) 当且仅当'userId'
和'customerId'
被评估为相等时!。要实现限制,我想考虑两种方式
通过将 xml 文件 (example.xml) 中的
'userId'
和'customerId'
值注入(inject)到下面的表达式 1 中。我使用的表达方式 这是 Rob Winch 建议的(谢谢 Rob!)。然而, Spring 无法计算表达式。通过将外部属性文件 (example.properties) 中的
'userId'
和'customerId'
值注入(inject)表达式 2 以下。同样,spring 也无法计算这个表达式。@Service("..") or @Controller public class MyMainClass { //Expression 1 @PreAuthorize("@userBean.userId == @customerBean.customerId") public Boolean edit(User user, Customer custmer) { return true; } //Expression 2 ////I've tried other ways as well, but end up with similar exceptions @PreAuthorize("${user.id} == ${customer.id}") public Boolean edit(User user, Customer customer) { return true; } }
我的问题:
Q1。我必须在 @PreAuthorize
注释中放入哪些正确的表达式才能将 xml 文件 (example.xml) 或属性文件 (example.properties) 中的值注入(inject) @PreAuthorize( ...)
表达式,那么它可以很容易地求值吗?
Q2。如果我犯了除表达之外的错误,请指出我。
Q3。这对我来说就像一个 1,000,000.00 美元的问题,因为我受够了解决这个问题!!!所以请尽可能地帮助我!
最佳答案
如果您正在使用属性文件并且想在 Controller 类中访问它们,您必须添加 <context:property-placeholder location="classpath:my.properties"/>
在您的 servlet 上下文 xml 文件中,之后您可以使用 @Value 注释来获取该属性的值。例如
my.properties
文件包含 some.userid=33
所以您可以使用以下方式访问此属性:
@Value("${some.userid}")
private int someId;
但为了确保测试目的,我会将 ignoreUnresolvablePlaceholders 设置为 false,以防万一它无法解析属性文件,我会知道错误来自何处...
希望对您有所帮助。
关于java - 将属性文件或 xml 文件中的属性值注入(inject) PreAuthorize(...) java 注释(未解决),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19774655/