开发者社区> 问答> 正文

JUnit+Spring+log4j+mybatis,测试时,控制台用log4j打印sql等状态

详细一点谢谢,网上找了好多,大多都一样..不能解决我的问题。求大神帮忙解决

展开
收起
a123456678 2016-03-18 09:45:19 4723 0
2 条回答
写回答
取消 提交回答
  • 不知道是否曲解了楼主的意思。由于一般而言需要配置连接池,因此我使用druid来实现打印SQL。
    链接:https://github.com/druid-io/druid

    2019-07-17 19:05:55
    赞同 展开评论 打赏
  • 首先推荐 将log4j 换成 logback

    如果非得用log4j的话,需要自己完成加载log4j配置文件的功能,因为通常log4j配置的加载都是通过WEB.XML文件进行的。

    如何让spring容器加载log4j的配置呢,我们看一下

    public abstract class Log4jConfigurer
    
    
    这是一个抽象类,所以我们需要借助spring的工厂来操作这个Log4jConfigurer,直接给代码吧
    
    public class MytMethodInvokingFactoryBean extends MethodInvokingFactoryBean implements InitializingBean {
        @Override
        public void afterPropertiesSet() throws Exception {
            super.afterPropertiesSet();
            Object[] args = getArguments();
            for (int i = 0; i < args.length; i++) {
                Object obj = args[i];
                if (obj instanceof String) {
                    String arg =obj.toString();
                    if(arg.startsWith("classpath:")||arg.startsWith("classpath*:")){
                        arg=arg.split(":")[1];
                        arg=this.getClass().getClassLoader().getResource(arg).getPath();
                        args[i]=arg;
                    }
                }
            }
            setArguments(args);
        }
    }
    
    
    spring配置文件添加
    
    <bean id="log4jInitialization"
              class="MytMethodInvokingFactoryBean">
            <property name="targetClass"
                      value="org.springframework.util.Log4jConfigurer" />
            <property name="targetMethod" value="initLogging" />
            <property name="arguments">
                <list>
                    <value>classpath:cfg/log4j.xml</value>
                </list>
            </property>
        </bean>
    
    
    这样初始化spring容器的时候就会加载log4j的配置了,junit的时候可以通过代码或者注解的方式初始化spring容器,log4j 级别设置成 trace 或者 debug ,下面给出一个junit的基础测试类
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(locations={"classpath:spring.xml"})
    public class BaseTest {
         
        @Autowired
        protected ApplicationContext applicationContext;
    }
    2019-07-17 19:05:55
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
workshop专场-微服务专场-开发者动手实践营-微服务-Spring Cloud Alibaba 微服务全家桶体验 立即下载
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载