2015-03-19 98 views

回答

3

这是一个Spring Security Framework注释,它允许只有在调用者具有ROLE_USERROLE_ADMIN安全角色时才能执行该方法。

有关Spring Security的更多信息,请参阅documentation

0

这里去一个例子:

@Controller 
public class ProtectedMethodsController { 

    @Secured({"ROLE_USER","ROLE_ADMIN"})//->for both security roles 
    @RequestMapping("/protectedMethod") 
    public @ResponseBody String secretMethod() { 
     return "You executed the protected method successfully (For USERs)"; 
    } 

    @Secured("ROLE_ADMIN") 
    @RequestMapping("/adminProtectedMethod") 
    public @ResponseBody String adminSecretMethod() { 
     return "You executed the protected method successfully (For ADMINs)"; 
    } 

    //->Without @Secured("ROLE_") 
    @RequestMapping("/notProtectedMethod") 
    public @ResponseBody String notProtectedMethod() { 
     return "You executed the not protected method successfully (For ALL USERs)"; 
    } 

    /** Notes: 
    * 1 - The first step is to enable method security, you do that annotating 
    *  the main class (class with the @SpringBootApplication annotation) 
    *  with @EnableGlobalMethodSecurity(securedEnabled = true); 
    * 2 - Then we can decorate the method resources with @Secured("ROLE_USER") 
    *  annotation.**/ 

} 


@SpringBootApplication 
@EnableGlobalMethodSecurity(securedEnabled = true) 
public class Application extends SpringBootServletInitializer { 

    public static void main(String[] args) throws Throwable { 
     SpringApplication.run(Application.class, args); 
    } 

    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(Application.class); 
    } 
}