如何在安全上下文中从应用程序上下文调用带有@Autowiring的bean

时间:2016-02-25 09:39:29

标签: java spring spring-security

经过研究,我仍然没有找到解决这个问题的方法。

我的目标是使用数据库验证自定义身份验证提供程序中的用户,但@Autowiring始终抛出空指针异常。

这是我的代码:

自定义身份验证提供程序:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private Validator iValidate;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException{         
        if (iValidate.userNameCheck(auth.getName()) != "00") {
            auth=null;
        }     
        return auth:            
    }

    @Override
    public boolean supports(Class<?> auth) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(auth));
    }

}

Validator.java:

@Component
public class Validator implements IsamSvc {

    private StopWatch sw = new StopWatch();

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String userNameCheck(String mercid, String caller) {

        /////validating code/////
    }   
}

Spring Security XML:

<global-method-security pre-post-annotations="enabled" />



<http pattern="/resources/**" security="none" />
<http auto-config="false" use-expressions="true" disable-url-rewriting="true" >


    <session-management session-fixation-protection="newSession" session-authentication-error-url="/login.do?sessionalreadyexist">
        <concurrency-control max-sessions="1" expired-url="/login.do?expired" error-if-maximum-exceeded="true" />
    </session-management>

    <intercept-url pattern="/clearcache" access="permitAll()" />
    <intercept-url pattern="/login.do" access="permitAll()" />
    <intercept-url pattern="/**" access="isFullyAuthenticated()" />

    <logout logout-success-url="/login.do?logout" delete-cookies="JSESSIONID" invalidate-session="true" />
    <access-denied-handler error-page="/403" />

 <form-login login-page='/login.do' login-processing-url="/login" default-target-url="/main" always-use-default-target="true" authentication-failure-url="/login.do?error" username-parameter="username"    password-parameter="password" authentication-details-source-ref="CustomAuthInfoSource" /> -->

</http>

<authentication-manager>
    <authentication-provider ref="CustomAuthenticationProvider" />
</authentication-manager>

<beans:bean id="CustomAuthenticationProvider" class="xx.xxx.xxxx.xxxxx.CustomAuthenticationProvider" />

beans.xml中:

<beans:bean id="iValidate" class="xx.xxx.xxxx.xxxxx.Validator" scope="prototype" />

/////// Other beans ////////

当我在@Controller类中调用@Autowired private Validator iValidate;时,它正常工作,但在CustomAuthenticationProvider中,它将返回null ...

任何解决方案?

1 个答案:

答案 0 :(得分:2)

使用CustomAuthenticationProvider注释

注释@Component