SpringBoot配置文件——加载顺序

SpringBoot配置文件——加载顺序 配置文件所在目录 file:./config/ 根目录中的config目录中 file:./ 根目录中 classpath:/config/ resource目录中的config目录下 classpath:/ resource目录下(类路径下 classpath) 读取顺序(优先级顺序) 如果在不同的目录中存在多个配置文件,它的读取顺序是: 1、config/application.properties(项目根目录中config目录下) 2、config/application.yml 3、application.properties(项目根目录下) 4、application.yml 5、resources/config/application.properties(项目resources目录中config目录下) 6、resources/config/application.yml 7、resources/application.properties(项目的resources目录下) 8、resources/application.yml 结论: 配置的优先级如上所示,如果同一个配置配置在多个配置文件中,则优先使用先读取到的,也就是说,1-8的优先级是由高到低的 PS: 创建SpringBoot项目时,一般的配置文件放置在项目的resources目录下,因为配置文件的修改,通过热部署不用重新启动项目,而热部署的作用范围是classpath下 参考: springboot官方文档:https://docs.spring.io/spring-boot/docs/2.3.3.RELEASE/reference/html/spring-boot-features.html#boot-features-external-config

September 27, 2024

Spring的启动流程--注解方式启动

Bean生命周期 Spring的启动流程–注解方式启动 1. 创建AnnotationConfigApplicationContext 1.1 创建beanFactory this.beanFactory = new DefaultListableBeanFactory(); 1.2 创建Reader this.reader = new AnnotatedBeanDefinitionReader(this); 关注 /* * 将一些RootBeanDefinition注册进DefaultListableBeanFactory */ AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, @Nullable Object source) { DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8); if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); } if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); } // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); } // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); } if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME)); } if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME)); } return beanDefs; } 1.3 创建Scancer this.scanner = new ClassPathBeanDefinitionScanner(this); 关注 ...

September 27, 2024

spring boot运行非web项目

前言 一直以来,一直使用springboot来创建基于web的项目,今天突然想到,springboot是否可以用于非web项目的使用。 非web运行办法 启动类main方法后面执行 @SpringBootApplication public class StudyLockApp { public static void main(String[] args) { ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(StudyLockApp.class, args); RedisService redisService = configurableApplicationContext.getBean(RedisService.class); Boolean lock = redisService.getLock("lock", 1); System.out.println(lock); } } 通过SpringApplication.run拿到bean容器 获取到已经注入进去的业务bean 执行相应的方法 实现ApplicationRunner接口 @SpringBootApplication public class StudyLockApp implements ApplicationRunner, ApplicationContextAware { private ApplicationContext applicationContext; public static void main(String[] args) { SpringApplication.run(StudyLockApp.class, args); } @Override public void run(ApplicationArguments args) throws Exception { RedisService redisService = applicationContext.getBean(RedisService.class); for(int i = 0;i<10;i++){ Thread thread = new Thread(new ConsumerThread(i,redisService)); thread.start(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } } 实现CommandLineRunner接口 @SpringBootApplication public class StudyLockApp implements CommandLineRunner, ApplicationContextAware { private ApplicationContext applicationContext; public static void main(String[] args) { SpringApplication.run(StudyLockApp.class, args); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void run(String... args) throws Exception { RedisService redisService = applicationContext.getBean(RedisService.class); for(int i = 0;i<10;i++){ Thread thread = new Thread(new ConsumerThread(i,redisService)); thread.start(); } } } Springboot源码 public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); configureIgnoreBeanInfo(environment); Banner printedBanner = printBanner(environment); context = createApplicationContext(); exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); prepareContext(context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } listeners.started(context); callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try { listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context; } 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) { callRunner((ApplicationRunner) runner, args); } if (runner instanceof CommandLineRunner) { callRunner((CommandLineRunner) runner, args); } } } private void callRunner(ApplicationRunner runner, ApplicationArguments args) { try { (runner).run(args); } catch (Exception ex) { throw new IllegalStateException("Failed to execute ApplicationRunner", ex); } } private void callRunner(CommandLineRunner runner, ApplicationArguments args) { try { (runner).run(args.getSourceArgs()); } catch (Exception ex) { throw new IllegalStateException("Failed to execute CommandLineRunner", ex); } } 其实就是在执行容器初始化后再调用实现的run方法而已。

September 27, 2024
苏ICP备2021016520号-1