2013-11-11 4 views
1

Для источника данных слоя я использую следующий файл конфигурации 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 является не подключен. Что я могу сделать, чтобы решить эту проблему?

ответ

1

Что я нашел. Аналогичный вопрос уже выполнены: same1, some solutions

seems the problem is not connected, but the last answer is the best solution

всего: На самом деле, поле, которое вводится с @Inject не может быть пустым. Он должен вызывать исключение. В результате, если оно равно нулю, аннотация вообще не применяется. В результате основной причиной является отсутствие его реализации в classpath.

Итак, я добавил следующее в свой web.pom. и решить эту проблему:

<dependency> 
    <groupId>javax.inject</groupId> 
    <artifactId>javax.inject</artifactId> 
    <version>1</version> 
</dependency> 

В качестве альтернативных вариантов я мог бы использовать:

  1. @Resource вместо @Inject, и окружающая среда была установлена.

  2. Передано envirionment как аргумент в конструктор вместо его проводки через аннотацию. Но лучший случай, ИМХО, - это исправление jar dependecy.

Смежные вопросы