Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for making MapAccessor read-only #33222

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -33,10 +33,30 @@
*
* @author Juergen Hoeller
* @author Andy Clement
* @author Yanming Zhou
* @since 3.0
*/
public class MapAccessor implements CompilablePropertyAccessor {

private final boolean allowWrite;

/**
* Create a new map accessor for reading as well as writing.
* @see #MapAccessor(boolean)
*/
public MapAccessor() {
this(true);
}

/**
* Create a new map accessor for reading and possibly also writing.
* @param allowWrite whether to allow write operations on a target instance
* @see #canWrite
*/
public MapAccessor(boolean allowWrite) {
this.allowWrite = allowWrite;
}

@Override
public Class<?>[] getSpecificTargetClasses() {
return new Class<?>[] {Map.class};
Expand All @@ -60,7 +80,7 @@ public TypedValue read(EvaluationContext context, @Nullable Object target, Strin

@Override
public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
return true;
return this.allowWrite;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
* Tests for {@link MapAccessor}.
*
* @author Andy Clement
* @author Yanming Zhou
*/
class MapAccessorTests {

Expand Down Expand Up @@ -80,6 +81,16 @@ void mapAccessorCompilable() {
assertThat(ex.getValue(sec,testMap)).isEqualTo("bar2");
}

@Test
void mapAccessorNotWritable() {
Map<String, Object> testMap = getSimpleTestMap();
StandardEvaluationContext sec = new StandardEvaluationContext();
sec.addPropertyAccessor(new MapAccessor(false));
SpelExpressionParser sep = new SpelExpressionParser();
Expression ex = sep.parseExpression("foo");
assertThat(ex.isWritable(sec, testMap)).isFalse();
}

public static class MapGetter {
Map<String,Object> map = new HashMap<>();

Expand Down