2012-10-19 30 views
0

非常簡單的場景:我使用Spring和Spring Security,並且我試圖將一個屬性注入到我的AuthenticationManager使用的AuthenticationProvider中。我只是認爲我可以將它連接到applicationContext中,但不確定這是否可行。如何將一個屬性注入到我沒有實例化的對象中?

的applicationContext.xml:

<http use-expressions="true"> 
    <intercept-url pattern="/" access="permitAll" /> 
    <intercept-url pattern="/**" access="hasRole('USER')"/> 
    <form-login login-page="/index" /> 
</http> 

<authentication-manager alias="authenticationManager"> 
    <authentication-provider ref="twitterAuthenticationProvider" /> 
</authentication-manager> 

<beans:bean id="twitterAuthenticationProvider" class="com.bottlingday.model.auth.TwitterAuthenticationProvider" /> 

TwitterAuthenticationProvider:

public class TwitterAuthenticationProvider implements AuthenticationProvider 
{ 
@Autowired 
private AppEngineUserStore userStore; 

static Log log = LogFactory.getLog(TwitterAuthenticationProvider.class.getName()); 

public void Test() 
{ 
      //userStore is always null here 
    log.info("test"); 
} 
} 

在我的控制器失敗,因爲userStore是TwitterAuthenticationProvider空裁判:

Authentication authentication = this.authenticationManager.authenticate(authToken); 

這裏是確切的錯誤:

java.lang.NullPointerException 
at com.bottlingday.model.auth.TwitterAuthenticationProvider.authenticate(TwitterAuthenticationProvider.java:33) 
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156) 
at com.bottlingday.auth.TwitterAuthController.OauthCallback(TwitterAuthController.java:129) 

編輯:我正在使用自動裝配,它適用於其他事情。如果我在MVC控制器中自動裝入一個AppEngineUserStore,它每次都會在那裏。

回答

1
I just had the thought that I might be able to wire it up in the applicationContext, but not sure if that would work. 

這會奏效。您可以在應用程序上下文中指定屬性的接線。 然而,這是不一樣的自動連接(這是你在你的AuthenticationProvider

如果你想自動裝配你AppEngineUserStore你需要在你的應用程序上下文註冊並開啓自動裝配。這可以做如下:

<context:annotation-config /> 

Spring也可以掃描豆自動裝配,如果你使用:

<context:component-scan base-package="com.my.package" /> 

氏s將自動啓用自動裝配

+0

我正在使用自動裝配,它正在工作。請參閱編輯 – MStodd

+0

這是您唯一的應用程序配置文件嗎? –

+0

我的servlet也有一個上下文。那個包含 MStodd

0

如果您使用自動裝配,則表示您在春季環境中使用了Annoations。

<context:annotation-config /> 

否則你需要做基於xml的DI。

+0

我正在使用自動裝配,並且其他東西都接線良好 – MStodd

相關問題