我可以在注解上使用@PreAuthorize吗?
在Spring中,我可以在注释中使用诸如Component和DependsOn之类的注释,如下所示:
@Target(ElementType.TYPE)
@Component
@DependsOn(CoreInitializerConfig.ROLE_INITIALIZER_ID)
public @interface WebComponent
{
}
而且效果很好.但是当我尝试以相同的方式使用PreAuthorize时:
@Target(
{
ElementType.TYPE, ElementType.METHOD
})
@Component
@PreAuthorize("hasAuthority('PERM_READ_SETTINGS')")
public @interface SettingsAuthorized
{
}
不起作用,我在MVC Controller pojo和Bean的方法中尝试了一下,但没有起作用,我不得不明确地指出:
@Controller
@PreAuthorize("hasAuthority('PERM_READ_SETTINGS')")
public class SettingsController
{
...
}
解决方法:
我通过添加@Retention(RetentionPolicy.RUNTIME)解决了问题
还建议将@Documented和@Inherited添加到最终注释中,这样可以得到:
@Target(
{
ElementType.TYPE, ElementType.METHOD
})
@Component
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@PreAuthorize("hasAuthority('PERM_READ_SETTINGS')")
public @interface SettingsAuthorized
{
}
标签:spring-security,annotations,spring,java,spring-mvc
来源: https://codeday.me/bug/20191120/2040738.html