加载配置文件

前言:如果我们需要调用某个方法,其中的参数为可更改,我们最好是采用配置文件的方式来写,这样便于管理

比如我在写一个通过SFTP连接服务器的环节

public class SFTPUtil {
    
    private static Logger log=Logger.getLogger(SFTPUtil.class.getName());
    
    private String host;//服务器连接ip
    private String username;//用户名
    private String password;//密码
    private int port=22;//端口号
    private ChannelSftp sftp=null;
    private Session sshSession=null;
    
    
    public SFTPUtil(String host, String username, String password, int port) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
    }


    public SFTPUtil(String host, String username, String password) {
        super();
        this.host = host;
        this.username = username;
        this.password = password;
    }
    
    /**
     *ͨ通过SFTP连接服务器
     */
    public void connect(){
        try {
            JSch jsch=new JSch();
            jsch.getSession(username, host, port);
            //����session
            sshSession=jsch.getSession(username, host, port);
            if(log.isInfoEnabled()){
                log.info("Session created.");
            }
            sshSession.setPassword(password);
            Properties sshConfig=new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            if(log.isInfoEnabled()){
                log.info("Session connected.");
            }
            Channel channel=sshSession.openChannel("sftp");
            channel.connect();
            if(log.isInfoEnabled()){
                log.info("Opening channel.");
            }
            sftp=(ChannelSftp)channel;
            if(log.isInfoEnabled()){
                log.info("Connected to "+host+".");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
View Code

1.Properties文件

以key-value的形式写入参数

2.加载properties的工具类

package com.copote.commons.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ConfigurableConstants {
    
    public static Log logger = LogFactory.getLog(ConfigurableConstants.class);
    public static Properties p = new Properties();

        /**
         * 静态读入属性文件到Properties p变量中
         */
        public  static  void init() {
            InputStream in = null;
            try {
                in = ConfigurableConstants.class.getClassLoader().getResourceAsStream("config.properties");             
                if (in != null)
                    p.load(in);            
            } catch (IOException e) {
                logger.error("load config.properties into Constants error!");
            }
            finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        logger.error("close config.properties error!");
                    }
                }
            }
        }

        /**
         * 封装了Properties类的getProperty函数,使p变量对子类透明.
         *
         * @param key          property key.
         * @param defaultValue 当使用property key在properties中取不到值时的默认值.
         */
        public static String getProperty(String key) {
            return p.getProperty(key);
        }
        
        public static void main(String[] args){
            ConfigurableConstants.init();
            System.out.println(ConfigurableConstants.getProperty("host"));
        }
}
View Code

3.调用


方式2:Springboot项目通过@configurationProperties注解

@Configuration
@ConfigurationProperties(ignoreInvalidFields = false)
@PropertySource("classpath:config.properties")
@Data
@Component
public class PropertiesConfig {
    private String druidUserName;
    private String druidPassword;
    private String druidUrlMapping;
    private String druidAllow;
    private String druidDeny;
    private String druidResetEnable;
}

使用时直接注入即可

@Autowired
private PropertiesConfig config;
原文地址:https://www.cnblogs.com/wutongshu-master/p/11738651.html