zoukankan      html  css  js  c++  java
  • 计时器与启动加载器

    计时器

    import org.junit.jupiter.api.Test;
    import org.springframework.util.StopWatch;
    
    public class StopWatchDemo {
        @Test
        public void test() throws InterruptedException {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start("task1");
            Thread.sleep(2000L);
            stopWatch.stop();
            stopWatch.start("task2");
            Thread.sleep(3000L);
            stopWatch.stop();
            stopWatch.start("task3");
            Thread.sleep(1000L);
            stopWatch.stop();
            System.out.println(stopWatch.prettyPrint());
        }
    }
    
    
    StopWatch '': running time = 6008888191 ns
    ---------------------------------------------
    ns         %     Task name
    ---------------------------------------------
    2004276665  033%  task1
    3003999368  050%  task2
    1000612158  017%  task3
    

    启动加载器

    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    /**
     * 启动加载器
     * @see SpringApplication#callRunners(org.springframework.context.ApplicationContext, org.springframework.boot.ApplicationArguments)
     * {@link CommandLineRunner}
     */
    @Component
    @Order
    public class FirstCommandLineRunner implements CommandLineRunner {
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("u001B[32m First CommandLineRunner");
        }
    }
    
    
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    /**
     * 启动加载器
     * {@link ApplicationRunner}
     */
    @Order
    @Component
    public class FirstApplicationRunner implements ApplicationRunner{
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("u001B[32m First ApplicationRunner");
        }
    }
    

    源码

    	private void callRunners(ApplicationContext context, ApplicationArguments args) {
    		List<Object> runners = new ArrayList<>();
    		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); //判断类型
    		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    		AnnotationAwareOrderComparator.sort(runners); //排序 
    		for (Object runner : new LinkedHashSet<>(runners)) {
    			if (runner instanceof ApplicationRunner) {   //ApplicationRunner先执行
    				callRunner((ApplicationRunner) runner, args);
    			}
    			if (runner instanceof CommandLineRunner) {
    				callRunner((CommandLineRunner) runner, args);
    			}
    		}
    	}
    

    getBeansOfType

    	@Override
    	public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
    			throws BeansException {
    
    		assertBeanFactoryActive();
    		return getBeanFactory().getBeansOfType(type, includeNonSingletons, allowEagerInit);
    	}
    

    assertBeanFactoryActive

    	protected void assertBeanFactoryActive() {
    		if (!this.active.get()) {  //是在refreshContext->org.springframework.context.support.AbstractApplicationContext#prepareRefresh赋值的
    			if (this.closed.get()) {
    				throw new IllegalStateException(getDisplayName() + " has been closed already");
    			}
    			else {
    				throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
    			}
    		}
    	}
    
    org.springframework.context.support.AbstractApplicationContex#prepareRefresh
    protected void prepareRefresh() {
    		// Switch to active.
    		this.startupDate = System.currentTimeMillis();
    		this.closed.set(false);
    		this.active.set(true);
    

    ApplicationRunner对比CommandLineRunner

    • callRunner
            //ApplicationRunner
            private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
    		try {
    			(runner).run(args);
    		}
    		catch (Exception ex) {
    			throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
    		}
    	}
            //CommandLineRunner
    	private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
    		try {
    			(runner).run(args.getSourceArgs());
    		}
    		catch (Exception ex) {
    			throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
    		}
    	}
    

    ApplicationArguments初始化

    	ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    
    //最后执行的是org.springframework.core.env.SimpleCommandLineArgsParser#parse
    public CommandLineArgs parse(String... args) {
    		CommandLineArgs commandLineArgs = new CommandLineArgs();
    		for (String arg : args) {
    			if (arg.startsWith("--")) {
    				String optionText = arg.substring(2);
    				String optionName;
    				String optionValue = null;
    				int indexOfEqualsSign = optionText.indexOf('=');
    				if (indexOfEqualsSign > -1) {
    					optionName = optionText.substring(0, indexOfEqualsSign);
    					optionValue = optionText.substring(indexOfEqualsSign + 1);
    				}
    				else {
    					optionName = optionText;
    				}
    				if (optionName.isEmpty()) {
    					throw new IllegalArgumentException("Invalid argument syntax: " + arg);
    				}
    				commandLineArgs.addOptionArg(optionName, optionValue);
    			}
    			else {
    				commandLineArgs.addNonOptionArg(arg);
    			}
    		}
    		return commandLineArgs;
    	}
    
  • 相关阅读:
    [LeetCode] 75. Sort Colors 颜色排序
    [LeetCode] 76. Minimum Window Substring 最小窗口子串
    OpenCV 2.4.10 Linux Qt Conifguration
    OpenCV2.4.10 Mac Qt Configuration
    [LeetCode] Combinations 组合项
    [LeetCode] 79. Word Search 词语搜索
    OpenCV count the number of connected camera 检测连接的摄像头的数量
    OpenCV 2.4.11 VS2010 Configuration
    Qt 程序和窗口添加图标
    [LeetCode] 80. Remove Duplicates from Sorted Array II 有序数组中去除重复项之二
  • 原文地址:https://www.cnblogs.com/fly-book/p/12703437.html
Copyright © 2011-2022 走看看