如何在@DataJpaTest中使用用户定义的数据库代理

时间:2017-05-29 08:22:33

标签: spring-boot spring-boot-test

我们需要跟踪数据库指标,以便我们使用datasource-proxy来跟踪它,以便在我们创建的自定义数据源的spring boot项目中集成它 如下

@Component
@Slf4j
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceBeanConfig
{

    public DataSource actualDataSource()
    {
        EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
        return databaseBuilder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    @Primary
    public DataSource dataSource() {
        // use pretty formatted query with multiline enabled
        PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
        creator.setMultiline(true);

        log.info("Inside Proxy Creation");

        SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
        listener.setQueryLogEntryCreator(creator);

        return ProxyDataSourceBuilder
                .create(actualDataSource())
                .countQuery()
                .name("MyDS")
                .listener(listener)
                .build();
    }
}

当我们运行主应用程序时,数据源代理被选中,但是当我们使用@DataJpaTest时,它没有被提升。如何在JUNIT测试用例中启用数据源代理?

修改::

使用Spring BeanPostProcessor配置代理数据源

@Slf4j
@Configuration
public class DataSourceBeanConfig implements BeanPostProcessor
{
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException
    {

        if (bean instanceof DataSource)
        {
            System.out.println("AfterInitialization : " + beanName);

            // use pretty formatted query with multiline enabled
            PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
            creator.setMultiline(true);

            log.info("Inside Proxy Creation");

            SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
            listener.setQueryLogEntryCreator(creator);

            return ProxyDataSourceBuilder.create((DataSource) bean).countQuery()
                    .name("MyDS").listener(listener).build();

        }
        return bean; // you can return any other object as well
    }
}

1 个答案:

答案 0 :(得分:0)

这是我们需要创建TestConfiguration以在@DataJpaTest

中使用的解决方案
@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTestJPA
{

    @TestConfiguration
    static class ProxyDataSourceConfig implements BeanPostProcessor
    {
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException
        {

            if (bean instanceof DataSource)
            {
               return ProxyDataSourceBuilder
                            .create((DataSource) bean)
                            .countQuery()
                            .name("MyDS")
                            .build();
                // @formatter:on

            }
            return bean; // you can return any other object as well
        }
    }
}