学习SpringMVC中优秀的代码编写风格

org.springframework.web.servlet.FrameworkServlet 中有下面这段代码

    private class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {

        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            FrameworkServlet.this.onApplicationEvent(event);
        }
    }
    public void onApplicationEvent(ContextRefreshedEvent event) {
        this.refreshEventReceived = true;
        onRefresh(event.getApplicationContext());
    }

这里,ContextRefreshListener 是FrameworkServlet的内部类,监听Context-RefreshedEvent事件,当接收到消息时调用FrameworkServlet的onApplicationEvent方法,在onApplicationEvent中会调用一次onRefresh()方法,并将refreshEventReceived标志设置为已经refresh过。

这种写法,让我注意到FrameworkServlet.this.onApplicationEvent(event);这么一句代码,在内部类中使用外部类名.this.method就可以调用外部类的方法,看起来很不错的样子。所以,动手测试了一下,代码如下:

/**
 * Created by Administrator on 2016/6/25.
 */
public class Ha {
    private class Name {
        public void sayHello() {
            Ha.this.sayHello();
        }
    }

    public void sayHello() {
        System.out.println("Hello");
    }

    public void use() {
        Name name = new Name();
        name.sayHello();
    }

    public static void main(String[] args) {
        Ha ha = new Ha();
        ha.use();
    }
}

上面的代码太简单不过了,基本上没有逻辑,就不再解释了,写完问问我女票,看看她的回应,见下一节。

运行结果帮我来说明

运行结果

posted @ 2016-06-25 16:52  shugen  阅读(169)  评论(0编辑  收藏  举报