Can Spring evaluate all characters/expressions in SpEL expressions as they are injected from a property file?

我怕爱的太早我们不能终老 提交于 2019-11-29 11:51:28

The key to the answer is the way of how the the String literals are represented in SpEL. The following are valid:

  • The String literals in SpEL are presented with single quotes, e.g 'Hello' is a SpEL String literal.
  • All the values from a resource bundle are converted to String literals, which means that:
    • If you fetch a HELLO from a bundle in Java, you will receive a "HELLO" String literal.
    • If you fetch a HELLO from a bundle in SpEL, you will receive a 'HELLO' String literal.

Now let's take a look on the example you have above.

  1. In your first case, you have role1=ROLE_ADMIN in the resource bundle, which means that a 'ROLE_ADMIN' String literal will be created when evaluating ${role1}. This will result in @PreAuthorize("hasRole('ROLE_ADMIN')") annotation which is perfectly valid (if you have a ROLE_ADMIN role defined). That's why it's working and it is not surprising.

  2. In the second case, you have role2='ROLE_ADMIN' in the resource bundle, which means that a '''ROLE_ADMIN''' String literal will be created when the ${role2} is evaluated. Note that the ' sign is escaped by putting two ' characters. You receive an Access Denied error, simply because you don't have a 'ROLE_ADMIN' role, but ROLE_ADMIN (which is different).

  3. Your third guess is almost correct. The only thing you're not correct about is how the annotation would look like afted evaluating the #{role3} value in the resource bundle. As I mentioned, the ' is escaped in SpEL by putting two ' characters. Therefore, the annotation would look like @PreAuthorize("'hasRole('''ROLE_ADMIN''')'"). You're completely correct in your assumption that this is a String, not a Boolean expression and this is why the IllegalArgumentException is thrown.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!