本文主要是介绍java加载.properties配置文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java加载.properties配置文件
为了让代码比较规范,现在我们的常量都写进配置文件,写进去之后我们通过java怎么来加载这个配置文件呢?主要通过java.util.Properties类来实现。
一、代码结构
二、prop.properties配置文件
socket_port=8989
bootstrap_servers=138.82.52.11:9876,138.82.52.12:9876,138.82.52.13:9876
topic_name=spirits
三、Constants.java
package com.starit.ipran.load;import java.io.IOException;
import java.util.Properties;public class Constants {public static final short START_SIGN = 0X7EE7;// 开始标志// 配置文件定义的数据public static int SOCKET_PORT;// 远程服务端端口public static String BOOTSTRAP_SERVERS;// kafka服务器IPpublic static String TOPIC_NAME;// kafka主题名称static {Properties props = new Properties();try {props.load(ClassLoader.getSystemResourceAsStream("prop.properties"));SOCKET_PORT = Integer.parseInt(props.getProperty("socket_port"));BOOTSTRAP_SERVERS = props.getProperty("bootstrap_servers");TOPIC_NAME = props.getProperty("topic_name"); } catch (IOException e) {e.printStackTrace();}}
}
以上内容算是到此处完结,因为都是分享加载配置文件,下面继续分享java加载配置文件的两种方式
(1)pom.xml
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>3.2.4.RELEASE</version></dependency>
(2)CommonServiceContextLoad.java
package com.starit.ipran.load;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;/*** 加载配置文件**/
public final class CommonServiceContextLoad {private static ApplicationContext ctx = null;public static ApplicationContext init() {if (ctx == null) {ctx = new FileSystemXmlApplicationContext("classpath:spring-mybatis.xml");}return ctx;}/***传入bean id* @param beanName 获取到对应bean之后不需要强制转换* @return*/public static <T> T getBean(Class<T> clazz) {return init().getBean(clazz);}/***传入bean id* @param beanName 获取到对应bean之后需要强制转换* @return*/public static Object getBean(String beanName) {return init().getBean(beanName);}
}
(3)ApplicationContextHolder.java
package com.alarm.support;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 加载工具类*/
public class ApplicationContextHolder{private static ApplicationContext context = null;static{context = new ClassPathXmlApplicationContext("magnanimity-alarm-context.xml");}public static <T> T getBean(Class<T> clazz){return context.getBean(clazz);}public static Object getBean(String beanId){return context.getBean(beanId);}public static <T> T getBean(String beanId, Class<T> clazz){return context.getBean(beanId, clazz);}
}
这篇关于java加载.properties配置文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!