我正在使用 Spring Boot MVC,并且 Spring 的 ServletRegistrationBean
在我的数据源配置之前被调用,该配置在 StandardContext
中加载。
WebSecurityConfig
始终首先被调用,因此永远不会为 Autowired prodDatasource
定义 bean。
我尝试了从@Order
到@ConditionalOnMissingBean
的所有内容。我一直找不到合适的解释。但我需要在运行 WebSecurity 之前为数据源创建一个 Bean
应用程序(使用自动配置)
@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");
}
}
主数据源
@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());
}
}
最佳答案
嗯,我想出了一个似乎有帮助的解决方案。
而不是在我的 Spring Security 中使用@Autowire。我用 @Resource
替换了它们,它似乎在等待我的 bean 首先被创建。
关于java - Spring Security 找不到数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35563439/