java - 不同上下文中的 Spring bean 连接

标签 java spring spring-mvc configuration

对于数据源层,我使用以下 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 {
...

而且效果很好。

创建 DispatcherServlet 时,Web 模块中使用相同的 InfrastructureContextConfiguration 类:

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;
    }
}

但是现在,我在 InfrastructionContextConfiguration 的以下行中收到 NullPointerException:

dataSource.setDriverClassName(environment.getProperty("jdbc.driver"));

环境未连接。我该怎么做才能解决这个问题?

最佳答案

我发现了什么。类似的问题已经遇到了: same1, some solutions

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

总计: 实际上,@Inject注入(inject)的字段不能为null。它必须抛出异常。因此,如果它为空,那么 - 注释根本没有被应用。结果主要原因是类路径中没有实现。

所以我在 web.pom 中添加了以下内容。它解决了问题:

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

作为我可以使用的替代选项:

  1. @Resource而不是@Inject,并且环境已设置。

  2. 将环境作为参数传递给构造函数,而不是通过注释连接它。但恕我直言,最好的情况是修复 jar 依赖性。

关于java - 不同上下文中的 Spring bean 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19898626/

相关文章:

java - 有没有更好的方法来设置/运行这个Java程序?

Spring boot JobOperator.stop(executionId) 和 JobOperator.restart(executionId) 行为

java - Spring - 将 Web 表单绑定(bind)到 application.properties 文件

java - Spring Data JPA : query ManyToMany, 如何从映射的类获取数据?

java - Spring RestTemplate反序列化xml为对象返回null

java - 启动 Activity android 时聚焦 ListView 中的第一项

java - pom.xml 从 https ://start. spring.io/下载后显示错误

java - sdkmanager 返回相同的输出,无论传递给它的参数是什么

java - Spring Data 配置 - 找不到 hibernate.properties

java - 使用 MultipartFile 作为可选字段的多部分请求 - Spring MVC