2013-10-08 39 views
0

我有一个名为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 
    } 
} 

我检查每个输入,每次使用比导入文件以外的东西。

在不同的包装,它忽略了串内插:

package com.example.test.controller 

// imports excluded for brevity 

@Controller 
class UserController { 
    @Value('${com.example.test.admins}') 
    private String[] admins 

    public User get() { 
     def name = // Name gets put here 
     def admin = name in admins 
     println admins 
     println admin 
     return new User(name: name, admin: admin) 
    } 
} 

即产生该输出在控制台:

[${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不会更改任何东西。

+0

控制器可能使用servlet应用程序上下文,而不是根上下文。看到这个:http://stackoverflow.com/questions/11890544/spring-value-annotation-in-controller-class-not-evaluating-to-value-inside-pro – ataylor

+0

你是完全正确的。感谢您的链接。我会发布一个答案。 – lcarsos

回答

1

感谢@ ataylor指引我在正确的方向。

Spring中的控制器不使用相同的上下文。所以,我创建了一个服务,称为UserService

@Service 
class UserService { 
    @Value('${com.example.test.admins}') 
    private String[] admins 

    boolean getUserIsAdmin(String username) { 
     username in admins 
    } 

} 

而在UserController中的服务自动连接,它就像一个魅力。