markdown HOCON面向群众

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown HOCON面向群众相关的知识,希望对你有一定的参考价值。

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * A {@link PropertySourceFactory} (a Spring component allowing the usage of a custom {@link PropertySource}
 * implementation (e.g. different than a ".properties" file based) for the
 * {@link org.springframework.context.annotation.PropertySource @PropertySource} annotation) allowing the usage of
 * {@link Config TypeSafe Config} files (in, e.g., the famous HOCON format) as property sources.
 *
 * The default values for the application should be declared in a {@code reference.conf} file at the top of the
 * classpath (i.e. {@code src/main/resources/reference.conf}, typically), while the
 * {@link org.springframework.context.annotation.PropertySource#value()} shall point to a <strong>single</strong>
 * file containing the overrides.
 *
 * Example usage:
 *
 * <pre>
 * import com.typesafe.config.Config;
 * import org.springframework.beans.factory.annotation.Autowired;
 * import org.springframework.context.annotation.Bean;
 * import org.springframework.context.annotation.Configuration;
 * import org.springframework.context.annotation.PropertySource;
 * import org.springframework.core.env.ConfigurableEnvironment;
 *
 * &#064;PropertySource(
 *   // the specific value given below emulates the default Akka (and TC config in general) setup – the override file
 *   // will be pointed to by the "config.file" system property
 *   value = {"file:${config.file}"},
 *   factory = TypesafeConfigPropertySourceFactory.class,
 *   name = PROPERTY_SOURCE_NAME, // required only if using the bean declaration below
 * ignoreResourceNotFound = true)
 * &#064;Configuration
 * public class AppConfig {
 *
 * &#064;Autowired
 * private ConfigurableEnvironment e;
 *
 * static final String PROPERTY_SOURCE_NAME = "Typesafe Config Property Source";
 *
 * /&#42;&#42; OPTIONAL - allows for autowiring the Config bean as an alternative to autowiring the Environment object
 *   &#42; for resolving placeholders, since the Config API may be considered preferable by the Config-aware client code
 *   &#42;&#42;/
 * &#064;Bean
 * public Config typeSafeConfig() {
 * return ((org.springframework.core.env.PropertySource&lt;Config&gt;) e.getPropertySources()
 *   .get(PROPERTY_SOURCE_NAME))
 *   .getSource();
 * }
 * }
 * </pre>
 *
 * @see <a href="https://github.com/typesafehub/config">https://github.com/typesafehub/config</a>
 * @author jmelon.github.io
 * @since Spring 4.3
 */
public class TypesafeConfigPropertySourceFactory implements PropertySourceFactory {
    private static final Logger LOG = LoggerFactory.getLogger(TypesafeConfigPropertySourceFactory.class);

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Config config = ConfigFactory.parseFile(resource.getResource().getFile())
            .withFallback(ConfigFactory.load())
            .resolve();

        LOG.info("Creating property source named {} of {}:\n{}",
            name,
            config.origin(),
            config.root().render()
        );

        return new TypesafeConfigPropertySource(
            Optional.ofNullable(name).orElse("default"),
            config
        );
    }

    private static class TypesafeConfigPropertySource extends PropertySource<Config> {
        TypesafeConfigPropertySource(String name, Config source) {
            super(name, source);
        }

        @Override
        public Object getProperty(String path) {
            String pathWithoutColon = path.contains(":") ? path.substring(0, path.indexOf(':')) : path;
            if (source.hasPath(pathWithoutColon)) {
                return Optional.ofNullable(source.getAnyRef(pathWithoutColon))
                    .filter(property -> !(property instanceof Map))
                    .orElse(null);
            } else return null;
        }
    }
}
# companion to the `minimalisticSpringApp`
# BTW, this comment will get preserved when rendering the config in logs
minimalisticApp {
  valueAnnotationService {
    moneyToMakeInASingleBatch = 100
    currencies = ["USD", "PLN"]
  }

  envApiService {
    moneyToMakeInASingleBatch = 200
    currencies = ${minimalisticApp.valueAnnotationService.currencies}
    currencies += "GBP"
  }

  configApiService {
    moneyToMakeInASingleBatch = 300
    currencies = ${minimalisticApp.valueAnnotationService.currencies} ["EUR"]
  }

  # not really used in the example, just to show some syntax options
  someController {
    colons.are.fine.too : true
    uri.base = /some

    uri {
      moneyEndpoint = ${minimalisticApp.someController.uri.base}/money
      othreEndpoint = ${minimalisticApp.someController.uri.base}/other
    }
  }
}

someLibrary {
  database {
    uri = "jdbc:sth:whatever"
    password = "test123"
  }
}
// place next to the `app.conf` file
// then run with `groovy minimalisticSpringApp.groovy`
//


@Grab(group = 'com.typesafe', module = 'config', version = '1.3.3')
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
@Grab(group='ch.qos.logback', module='logback-classic', version='1.2.3')
import org.slf4j.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
@Grab(group = 'org.springframework', module = 'spring-context', version = '5.1.3.RELEASE')
import org.springframework.context.annotation.*
import org.springframework.core.env.Environment
import org.springframework.core.io.support.EncodedResource
import org.springframework.core.io.support.PropertySourceFactory

// ⚠️#1⚠️ Extremely minimalistic groovy/spring/typesafe config app
//   -- requires only an app.conf to be present at the execution path
def ctx = new AnnotationConfigApplicationContext(AppConfig.class)

println("

以上是关于markdown HOCON面向群众的主要内容,如果未能解决你的问题,请参考以下文章

将 Hocon 配置读取为 Map[String, String],其中键为点符号和值

markdown 学习 - 面向对象的编程

markdown 面向对象的JavaScript

markdown 面向前端开发人员的10个流行的JavaScript面试问题

markdown [Sandi Metz的实用面向对象设计注释] #design_pattern

Markdown 基本语法