Skip to content

Commit 9b34400

Browse files
committedJul 17, 2024·
Merge pull request #33222 from quaff
* pr/33222: Polish "Add support for making MapAccessor read-only" Add support for making MapAccessor read-only Closes gh-33222
2 parents ec383f6 + 821109b commit 9b34400

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed
 

‎spring-context/src/main/java/org/springframework/context/expression/MapAccessor.java

+23-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2021 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -37,6 +37,27 @@
3737
*/
3838
public class MapAccessor implements CompilablePropertyAccessor {
3939

40+
private final boolean allowWrite;
41+
42+
/**
43+
* Create a new map accessor for reading as well as writing.
44+
* @since 6.2
45+
* @see #MapAccessor(boolean)
46+
*/
47+
public MapAccessor() {
48+
this(true);
49+
}
50+
51+
/**
52+
* Create a new map accessor for reading and possibly also writing.
53+
* @param allowWrite whether to allow write operations on a target instance
54+
* @since 6.2
55+
* @see #canWrite
56+
*/
57+
public MapAccessor(boolean allowWrite) {
58+
this.allowWrite = allowWrite;
59+
}
60+
4061
@Override
4162
public Class<?>[] getSpecificTargetClasses() {
4263
return new Class<?>[] {Map.class};
@@ -60,7 +81,7 @@ public TypedValue read(EvaluationContext context, @Nullable Object target, Strin
6081

6182
@Override
6283
public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
63-
return true;
84+
return this.allowWrite;
6485
}
6586

6687
@Override

‎spring-context/src/test/java/org/springframework/context/expression/MapAccessorTests.java

+10
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,16 @@ void mapAccessorCompilable() {
8080
assertThat(ex.getValue(sec,testMap)).isEqualTo("bar2");
8181
}
8282

83+
@Test
84+
void mapAccessorNotWritable() {
85+
Map<String, Object> testMap = getSimpleTestMap();
86+
StandardEvaluationContext sec = new StandardEvaluationContext();
87+
sec.addPropertyAccessor(new MapAccessor(false));
88+
SpelExpressionParser sep = new SpelExpressionParser();
89+
Expression ex = sep.parseExpression("foo");
90+
assertThat(ex.isWritable(sec, testMap)).isFalse();
91+
}
92+
8393
public static class MapGetter {
8494
Map<String,Object> map = new HashMap<>();
8595

0 commit comments

Comments
 (0)
Please sign in to comment.