这篇文章主要介绍Java中如何获取properties文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

spring下获取Properties方式

比如已有的commonConfig.properties

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

在spring中引用commonConfig.properties

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

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

importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;@ComponentpublicclassConfig{@Value("${main.db.url}")publicStringjdbcUrl;}

controller

@RequestMapping("/service/**")@ControllerpublicclassTestController{@Value("${main.db.url}")privateStringjdbcUrl;//直接在Controller引用@RequestMapping(value={"/test"})publicModelMaptest(ModelMapmodelMap){modelMap.put("jdbcUrl",Config.jdbcUrl);returnmodelMap;}}第3种:不要在spring.xml中引用commonConfig.properties,在类注入时引用,然后使用Environment获取它的值

importorg.apache.commons.lang3.tuple.Pair;importorg.redisson.Config;importorg.redisson.Redisson;importorg.redisson.SentinelServersConfig;importorg.redisson.SingleServerConfig;importorg.redisson.client.RedisClient;importorg.redisson.client.RedisConnection;importorg.redisson.client.protocol.RedisCommands;importorg.redisson.codec.SerializationCodec;importorg.redisson.misc.URIBuilder;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.PropertySource;importorg.springframework.core.env.Environment;@Configuration@PropertySource("classpath:resources/config/commonConfig.properties")publicclassRedissonConfig{@AutowiredprivateEnvironmentenv;@BeanpublicSerializationCodecserializationCodec(){returnnewSerializationCodec();}@BeanpublicConfigreddissonConfig()throwsException{StringjdbcUrl=env.getProperty("main.db.url");}//此为代码片段第4种:不需要借用spring,直接在类中读取.但要注意:(redisson.properties配置文件中不能有.句号),否则将报错

importjava.util.ResourceBundle;publicclassRedissionParamsUtil{/**配置文件地址*/privatefinalStringconfigPath="resources/config/redisson.properties";privatestaticRedissionParamsUtilparamsUtil;ResourceBundlebundle=null;/***单例模式获取实例*@returnMenuService*/publicstaticRedissionParamsUtilgetInstance(){if(null==paramsUtil){paramsUtil=newRedissionParamsUtil();}returnparamsUtil;}/***构造方法*/privateRedissionParamsUtil(){bundle=ResourceBundle.getBundle(configPath);}publicStringgetValue(Stringkey){returnbundle.getString(key);}publicstaticvoidmain(String[]args){System.out.println(RedissionParamsUtil.getInstance().getValue("jdbc_url"));}}

以上是“Java中如何获取properties文件”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!