在Spring中以字符串数组形式读入文件
我有一个名为在Spring中以字符串数组形式读入文件,spring,groovy,annotations,Spring,Groovy,Annotations,我有一个名为security.properties的文件,看起来如下: com.example.test.admins=username,username1,username2 我想把那个文件作为字符串数组读入。这实际上在一个包中起作用: package com.example.test.security import org.springframework.beans.factory.annotation.Value import org.springframework.ldap.core
security.properties
的文件,看起来如下:
com.example.test.admins=username,username1,username2
我想把那个文件作为字符串数组读入。这实际上在一个包中起作用:
package com.example.test.security
import org.springframework.beans.factory.annotation.Value
import org.springframework.ldap.core.DirContextOperations
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator
class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
@Value('${com.example.test.admins}')
private String[] admins
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(
DirContextOperations userData, String username) {
def roles = [new SimpleGrantedAuthority("user")]
if (username in admins)
roles.add(new SimpleGrantedAuthority("admin"))
roles
}
}
在控制台中生成此输出:
[${com.example.test.admins}]
false
唯一提到该文件的是security applicationContext.xml
<context:property-placeholder
location="classpath:security.properties"
ignore-resource-not-found="true"
ignore-unresolvable="true"/>
但是,将其复制到applicationContext.xml中不会改变任何东西。感谢@ataylor为我指明了正确的方向 Spring中的控制器不使用相同的上下文。因此,我创建了一个名为
UserService
的服务:
@Service
class UserService {
@Value('${com.example.test.admins}')
private String[] admins
boolean getUserIsAdmin(String username) {
username in admins
}
}
在UserController中,它在服务中自动连接,工作起来很有魅力。控制器可能使用的是servlet应用程序上下文,而不是根上下文。看这个:你完全正确。谢谢你的链接。我会发布一个答案。
@Service
class UserService {
@Value('${com.example.test.admins}')
private String[] admins
boolean getUserIsAdmin(String username) {
username in admins
}
}