zoukankan      html  css  js  c++  java
  • java 获取properties的几种方式

    spring下获取Properties方式

    比如已有的commonConfig.properties

    main.db.driverClassName=com.mysql.jdbc.Driver
    main.db.url=jdbc:mysql://cloudpkdbrw.xxx.com:3306/huagang?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    main.db.username=huagang
    main.db.password=xxxHGtest

    在spring中引用commonConfig.properties

    第1种.直接在spring的xml中使用

    <!-- 加载配置文件 -->
        <bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location">
                <value>classpath:/resources/config/commonConfig.properties</value>
            </property>
        </bean>

     <!--或者 引入多配置文件
           <context:property-placeholder location="classpath:/resources/config/commonConfig.properties,classpath:XXX.properties"/> 

    --> 
     
          
        <!-- 配置数据源 -->
        <bean id="ajbDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
            <!--驱动类 -->
            <property name="driverClass">
                <value>${main.db.driverClassName}</value>
            </property>
            <!--url连接串 -->
            <property name="jdbcUrl">
                <value>${main.db.url}</value>
            </property>
            <!--用户名 -->
            <property name="user">
                <value>${main.db.username}</value>
            </property>
            <!--密码 -->
            <property name="password">
                <value>${main.db.password}</value>
            </property>
            <!-- 连接池中保留的最小连接数 最小链接数 -->
            <property name="minPoolSize">
                <value>1</value>
            </property>
            <!--连接池中保留的最大连接数 最大连接数 -->
            <property name="maxPoolSize">
                <value>4</value>
            </property>
            <!-- 最大空闲的时间,单位是秒,无用的链接再过时后会被回收 -->
            <property name="maxIdleTime">
                <value>1800</value>
            </property>
            <!-- 在当前连接数耗尽的时候,一次获取的新的连接数 -->
            <property name="acquireIncrement">
                <value>1</value>
            </property>
            <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
                  属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
                  如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
            <property name="maxStatements">
                <value>0</value>
            </property>
            <!-- 连接池初始化时获取的链接数,介于minPoolSize和maxPoolSize之间 -->
            <property name="initialPoolSize">
                <value>1</value>
            </property>
            <!--每1分钟检查所有连接池中的空闲连接。Default: 0 -->
            <property name="idleConnectionTestPeriod">
                <value>60</value>
            </property>
            <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
            <property name="acquireRetryAttempts">
                <value>30</value>
            </property>
            <!-- #每100ms尝试一次 -->
            <property name="acquireRetryDelay">
                <value>100</value>
            </property>
            <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 
                获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
            <property name="breakAfterAcquireFailure">
                <value>false</value>
            </property>
            <!-- 防止长时间闲置而导致被mysql断开 因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 
                等方法来提升连接测试的性能。Default: false -->
            <property name="testConnectionOnCheckout">
                <value>false</value>
            </property>
            <!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false --> 
            <property name="testConnectionOnCheckin">
                <value>true</value>
            </property>
            <!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:
                测试的表必须在初始数据源的时候就存在。Default: null-->
            <property name="preferredTestQuery">
                <value>select 1 from dual</value>
            </property>
        </bean>

    第2种:在java 启动加Conifg库中或者在controller中调用

    import org.springframework.beans.factory.annotation.Value; 
    import org.springframework.stereotype.Component; 
       
    @Component 
    public class Config {  
          @Value("${main.db.url}")   
          public  String jdbcUrl;  
        
    } 

    controller

    @RequestMapping("/service/**") 
    @Controller 
    public class TestController{ 
        
             @Value("${main.db.url}") 
             private String jdbcUrl; //直接在Controller引用 
             @RequestMapping(value={"/test"})  
            public ModelMap test(ModelMap modelMap) {  
                   modelMap.put("jdbcUrl", Config.jdbcUrl); 
                   return modelMap;  
              } 
         
    } 

    第3种,不要在spring.xml中引用commonConfig.properties,在类注入时引用,然后使用Environment获取它的值

    import org.apache.commons.lang3.tuple.Pair;
    import org.redisson.Config;
    import org.redisson.Redisson;
    import org.redisson.SentinelServersConfig;
    import org.redisson.SingleServerConfig;
    import org.redisson.client.RedisClient;
    import org.redisson.client.RedisConnection;
    import org.redisson.client.protocol.RedisCommands;
    import org.redisson.codec.SerializationCodec;
    import org.redisson.misc.URIBuilder;
    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.Environment;
    
    @Configuration
    @PropertySource( "classpath:resources/config/commonConfig.properties" )  
    public class RedissonConfig {
        
        @Autowired
        private Environment env;
    
        @Bean
        public SerializationCodec serializationCodec() {
            return new SerializationCodec();
        }
    
        @Bean
        public Config reddissonConfig() throws Exception {
    
         String jdbcUrl= env.getProperty("main.db.url");
    }
              //此为代码片段

    第4种,不需要借用spring,直接在类中读取.但要注意:(redisson.properties配置文件中不能有.句号),否则将报错

    import java.util.ResourceBundle;
    
    
    public class RedissionParamsUtil {
        
        /** 配置文件地址 */
        private final String configPath = "resources/config/redisson.properties";
     
     
        private static RedissionParamsUtil paramsUtil;
        
        ResourceBundle bundle = null;
        
    
    
    
        /**
         * 单例模式获取实例
         * @return MenuService
         */
        public static RedissionParamsUtil getInstance(){
            if(null==paramsUtil){
                paramsUtil = new RedissionParamsUtil();
            }
            return paramsUtil;
        }
        /**
         * 构造方法
         */
        private RedissionParamsUtil(){
              bundle = ResourceBundle.getBundle(configPath);
      }
        public String getValue(String key){
               return bundle.getString(key);
     }
        public static void main(String[] args) {
            System.out.println(RedissionParamsUtil.getInstance().getValue("jdbc_url"));
        }
         
    }
  • 相关阅读:
    Maidsafe-去中心化互联网白皮书
    The Top 20 Cybersecurity Startups To Watch In 2021 Based On Crunchbase
    Top 10 Blockchain Security and Smart Contract Audit Companies
    The 20 Best Cybersecurity Startups To Watch In 2020
    Blockchain In Cybersecurity: 11 Startups To Watch In 2019
    004-STM32+BC26丨260Y基本控制篇(阿里云物联网平台)-在阿里云物联网平台上一型一密动态注册设备(Android)
    涂鸦开发-单片机+涂鸦模组开发+OTA
    000-ESP32学习开发-ESP32烧录板使用说明
    03-STM32+Air724UG远程升级篇OTA(阿里云物联网平台)-STM32+Air724UG使用阿里云物联网平台OTA远程更新STM32程序
    03-STM32+Air724UG远程升级篇OTA(自建物联网平台)-STM32+Air724UG实现利用http/https远程更新STM32程序(TCP指令,单片机程序检查更新)
  • 原文地址:https://www.cnblogs.com/fuanyu/p/14665779.html
Copyright © 2011-2022 走看看