我Application
用两种安全方法创建了一个 Spring 组件:
@Component
public class Application {
public void run() {
onlyAdminMethod();
onlyAdminMethod2();
}
@Secured( "ROLE_ADMIN" )
public void onlyAdminMethod() {
System.out.println( "Admin-only method called" );
}
@PreAuthorize( "hasRole('ROLE_ADMIN')" )
public void onlyAdminMethod2() {
System.out.println( "Admin-only method 2 called" );
}
}
我在那个 bean 上调用run()
方法,我从 Spring XML 上下文中获取:
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean( Application.class).run();
什么都没有发生 -即使没有身份验证并SecurityContextHolder.getContext().getAuthentication()
返回,方法也会正常调用null
我的春天 XML:
<context:annotation-config />
<context:component-scan base-package="practice" />
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="admin" password="stackoverflow" authorities="ROLE_USER,ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled"/>
我使用 Maven 依赖项Spring 3.2.4