2016-04-28 15 views
0

私はスプリングウェブのセキュリティとデータベースに問題があります。私は、メソッドが正常に呼び出されスプリングセキュリティの設定に失敗する

@Configuration 
@EnableWebSecurity 
public class BBSecurity extends WebSecurityConfigurerAdapter { 
    @Autowired 
    public void setDataSource(DataSource dataSource) { 
     this.dataSource = dataSource; 
    } 

    @Override 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
     JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> cfg = auth.jdbcAuthentication(); 
     cfg.dataSource(dataSource); 
     cfg.usersByUsernameQuery("SELECT user_name, password, true FROM user_data WHERE user_name=?"); 
     cfg.passwordEncoder(new MyPasswordEncoder()); 
     cfg.authoritiesByUsernameQuery("SELECT user_name, concat('ROLE_',role) FROM user_data WHERE user_name=?"); 
    } 
} 

を使用する場合は、しかし、ログに私はこの

Using default security password: 81456c65-b6fc-43ee-be41-3137d02b122b

と私のデータベースのコードが使用されることはありません参照してください。

場合は、代わりに、私は(同じクラスに)

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
    JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> cfg = auth.jdbcAuthentication(); 
    ... same config code as above 
} 

を使用し、それが正常に動作しますが、時にはconfigureGlobalsetDataSource前に呼び出され、それが使用された前dataSourceが注入されていなかったので、私はIllegalStateExceptionを取得します。

私は最初のメソッドを動作させるために必要なことを理解したいと思います。

@Autowiredの順番を制御する方法もあります。 @DependsOn(DataSource)configureGlobalを追加しても効果はありません。

+0

はconfigure' 'に' Autowired'を置くようにしてください方法。また、 'configureGlobal'と' configure'を同時に使いましたか? –

+0

autowiredをconfigureメソッドに置くことは、2番目のメソッドである 'AuthenticationManagerBuilder'の注入であり、configureのオーバーライドではありません。 configureは、http://stackoverflow.com/questions/35218354/difference-between-registerglobal-configure-configureglobal-configureglo – dcsalmon

+0

への答えに示唆されています。注入順序の問題を除いて、Autowiredの作業は、以前に 'AuthenticationManagerBuilder'が注入されることがあります'dataSource'ですが、なぜconfigureが動作するように見えるのか興味がありますが、設定された' AuthenticationManagerBuilder'はその後認証に使用されません。 – dcsalmon

答えて

0

利用代わりセッター・インジェクションフィールドインジェクション

@Configuration 
@EnableWebSecurity 
public class BBSecurity extends WebSecurityConfigurerAdapter { 
    @Autowired private DataSource dataSource; 

    @Override 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
     // Same stuff 
    } 
} 

それともconfigureGlobal方法に直接Datasourceを注入:

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception { 
    // same stuff 
} 
+1

クール、ありがとう!私はすぐに2つのオブジェクトを注入できることを知らなかった。 また、gremlinsがオーバーライドアプローチを失敗させたようです。再構築され、その仕組みも同様に機能しているようです。 – dcsalmon

関連する問題