2016-02-22 129 views
1

我在使用Spring Boot MVC和Spring的ServletRegistrationBean在我的數據源配置之前被調用,它在StandardContext中加載。Spring安全無法找到數據源

WebSecurityConfig總是被首先調用,因此決不會爲Autowired prodDatasource定義一個bean。

我試過從@Order@ConditionalOnMissingBean的所有內容。我一直無法找到一個體面的解釋。但我需要一個Bean爲數據源創建它運行WebSecurity

應用程序(使用AutoConfigurations)

@EnableAutoConfiguration 
@SpringBootApplication 
@EnableCaching 
public class Application { 


    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Bean 
    public CacheManager cacheManager() { 
     return new ConcurrentMapCacheManager("appInfo"); 
    } 

} 

PrimaryDataSource前

@Configuration 
@PropertySource({ "classpath:application.properties" }) 
@EnableTransactionManagement 
@EnableJpaRepositories(basePackages = "App.Models", 
     entityManagerFactoryRef = "prodEntityManager", 
     transactionManagerRef = "transactionManager" 
) 
public class PrimaryDatasourceConfig { 

    @Autowired 
    private Environment env; 

    @Bean 
    @ConfigurationProperties(prefix = "spring.datasource.prod") 
    public DataSource prodDataSource() { 
     EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory(); 
     factory.setDatabaseName("spring-social-quickstart"); 
     factory.setDatabaseType(EmbeddedDatabaseType.H2); 
     return factory.getDatabase(); 
    } 
} 

WebSecurityConfig

@Configuration 
@EnableWebSecurity 
@Import(PrimaryDatasourceConfig.class) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private DataSource prodDataSource; 

    SuperiorUserService jdbcDao; 

....... 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
       .jdbcAuthentication() 
       .dataSource(prodDataSource); 
     auth.authenticationProvider(authProvider()); 
    } 

} 

回答

0

嗯,我想出了一個似乎有所幫助的解決方案。

而不是在我的Spring Security中使用@Autowire。我用@Resource替換了它們,它似乎等待我的bean被首先創建。