使用ApplicaionContext读取配置文件

使用ApplicaionContext读取配置文件

场景:
从配置文件读取某一属性值,减少代码的修改,通过配置文件实现属性值更换

具体实现过程:
1、创建工具类获取ApplicationContext

	@Component
	public class SpringContextUtil implements ApplicationContextAware {
		private static ApplicationContext applicationContext;

		@Override
		public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
			this.applicationContext = applicationContext;
		}

		public ApplicationContext getApplicationContext() {
			return applicationContext;
		}

		public static Object getBean(String beanName){
			return applicationContext.getBean(beanName);
		}
	}

2、将要从配置文件中读取的属性封装成bean
(1)方法一

	@Component("SystemDefault")
	@Scope
	@ConfigurationProperties(prefix = "test.systemDefault")
	public class SystemDefault {
		private String needGroup;

		public String getNeedGroup() {
			return needGroup;
		}

		public void setNeedGroup(String needGroup) {
			this.needGroup = needGroup;
		}
	}

(2)方法二

    @Component("SystemDefault")
    @Scope("singleton")
    public class SystemDefault {
        private String needGroup;

        @Value("${test.systemDefault.needGroup}")
        public void setNeedGroup(String needGroup) {
            this.needGroup = needGroup;
        }
		
        public String getNeedGroup() {
            return needGroup;
        }
    }

3、在配置文件中指定属性值

	test:
	  systemDefault:
		needGroup: true

4、代码中获取属性值

        SystemDefault systemDefault = (SystemDefault) SpringContextUtil.getBean("SystemDefault");
        String platform = systemDefault.getNeedGroup();

猜你喜欢

转载自blog.csdn.net/qq_32657967/article/details/81811431