0
点赞
收藏
分享

微信扫一扫

【希赛网】软考高级系统架构每日一题总结

奋斗De奶爸 2023-11-03 阅读 37

本文主要研究一下springboot的SpringPropertyAction

SpringBootJoranConfigurator

org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java

class SpringBootJoranConfigurator extends JoranConfigurator {

	private LoggingInitializationContext initializationContext;

	SpringBootJoranConfigurator(LoggingInitializationContext initializationContext) {
		this.initializationContext = initializationContext;
	}

	@Override
	public void addInstanceRules(RuleStore rs) {
		super.addInstanceRules(rs);
		Environment environment = this.initializationContext.getEnvironment();
		rs.addRule(new ElementSelector("configuration/springProperty"), new SpringPropertyAction(environment));
		rs.addRule(new ElementSelector("*/springProfile"), new SpringProfileAction(environment));
		rs.addRule(new ElementSelector("*/springProfile/*"), new NOPAction());
	}

}

SpringPropertyAction

org/springframework/boot/logging/logback/SpringPropertyAction.java

class SpringPropertyAction extends Action {

	private static final String SOURCE_ATTRIBUTE = "source";

	private static final String DEFAULT_VALUE_ATTRIBUTE = "defaultValue";

	private final Environment environment;

	SpringPropertyAction(Environment environment) {
		this.environment = environment;
	}

	@Override
	public void begin(InterpretationContext context, String elementName, Attributes attributes) throws ActionException {
		String name = attributes.getValue(NAME_ATTRIBUTE);
		String source = attributes.getValue(SOURCE_ATTRIBUTE);
		Scope scope = ActionUtil.stringToScope(attributes.getValue(SCOPE_ATTRIBUTE));
		String defaultValue = attributes.getValue(DEFAULT_VALUE_ATTRIBUTE);
		if (OptionHelper.isEmpty(name) || OptionHelper.isEmpty(source)) {
			addError("The \"name\" and \"source\" attributes of <springProperty> must be set");
		}
		ActionUtil.setProperty(context, name, getValue(source, defaultValue), scope);
	}

	private String getValue(String source, String defaultValue) {
		if (this.environment == null) {
			addWarn("No Spring Environment available to resolve " + source);
			return defaultValue;
		}
		return this.environment.getProperty(source, defaultValue);
	}

	@Override
	public void end(InterpretationContext context, String name) throws ActionException {
	}

}

示例

<property name="LOGS" value="./logs" />
<springProperty scope="context" name="application.name" source="spring.application.name" />
<springProfile name="production">
    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/${application.name}.log</file>
        <!-- configuration -->
    </appender>
</springProfile>

小结

springboot的logback可以通过springProperty来引用spring environment中的属性在logback的配置文件中使用,其主要是通过SpringPropertyAction来实现的。

举报

相关推荐

0 条评论