Для источника данных слоя я использую следующий файл конфигурации Spring:Spring боб проводки в различных контекстах
@Configuration
@ComponentScan(basePackages = {"com.savdev.springmvcexample.repository", "com.savdev.springmvcexample.config"})
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.savdev.springmvcexample.repository"})
public class InfrastructureContextConfiguration {
...
@Configuration
@Profile(value = "file_based")
@PropertySource("classpath:/db/config/file_based.properties")
public static class FileBasedConfiguration {
@Inject
private Environment environment;
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource();
dataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
dataSource.setUrl(environment.getProperty("jdbc.url"));
dataSource.setUsername(environment.getProperty("jdbc.username"));
dataSource.setPassword(environment.getProperty("jdbc.password"));
return dataSource;
}
}
...
Для запуска тестов я загрузить эту конфигурацию с помощью @ContextConfiguration
:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { InfrastructureContextConfiguration.class, HsqldbEmbeddableDbStarterContextConfiguration.class })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional()
@ActiveProfiles(profiles = {"file_based", "test_data"})
public abstract class AbstractJpaJavaTestBase {
...
И это прекрасно работает.
Тот же класс InfrastructureContextConfiguration используется в веб-модуле, когда DispatcherServlet создан:
public class SpringMvcExampleWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerDispatcherServlet(servletContext);
}
private void registerDispatcherServlet(final ServletContext servletContext) {
WebApplicationContext dispatcherContext = createContext(WebMvcContextConfiguration.class, InfrastructureContextConfiguration.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
dispatcherServlet.setContextInitializers(new SpringMvcExampleProfilesInitializer());
ServletRegistration.Dynamic dispatcher;
dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private WebApplicationContext createContext(final Class<?>... annotatedClasses) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(annotatedClasses);
return context;
}
}
Но теперь, я получаю NullPointerException в следующей строке InfrastructureContextConfiguration
:
dataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
environment
является не подключен. Что я могу сделать, чтобы решить эту проблему?