java项目中的全局变量

1,全局配置类

“JAVA中不应该有所谓全局变量的概念,全局变量严重影响了封装和模块化,所以如果你的程序中需要所谓的全局变量,那一定是你对程序的设计出了问题。”
这句话我也不太理解,但是觉得项目里还是需要有所谓的全局配置,全局配置写在配置文件中,然后加载到项目里

/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.common.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.springframework.core.io.DefaultResourceLoader;

import com.ckfinder.connector.ServletContextFactory;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.PropertiesLoader;
import com.jeeplus.common.utils.StringUtils;

/**
 * 全局配置类
 * @author jeeplus
 * @version 2014-06-25
 */
public class Global {

    /**
     * 当前对象实例
     */
    private static Global global = new Global();

    /*
     * 
     */
    public static String APP_CACHE="APPCACHE";

    public static String APP_CACHE_checkcode="APPCACHEcheckcode";

    //public static String APP_CACHE_phone="APPCACHEphone";

    public static String APP_TOKEN="APPTOKEN";

    public static String APP_SHORT_CACHE="APPSHORTCACHE";

    /**
     * 保存全局属性值
     */
    private static Map<String, String> map = Maps.newHashMap();

    /**
     * 属性文件加载对象
     */
    private static PropertiesLoader loader = new PropertiesLoader("jeeplus.properties");

    /**
     * 显示/隐藏
     */
    public static final String SHOW = "1";
    public static final String HIDE = "0";

    /**
     * 是/否
     */
    public static final String YES = "1";
    public static final String NO = "0";

    /**
     * 对/错
     */
    public static final String TRUE = "true";
    public static final String FALSE = "false";

    /**
     * 上传文件基础虚拟路径
     */
    public static final String USERFILES_BASE_URL = "/userfiles/";

    /**
     * 获取当前对象实例
     */
    public static Global getInstance() {
        return global;
    }

    /**
     * 获取配置
     * @see ${fns:getConfig('adminPath')}
     */
    public static String getConfig(String key) {
        String value = map.get(key);
        if (value == null){
            value = loader.getProperty(key);
            map.put(key, value != null ? value : StringUtils.EMPTY);
        }
        return value;
    }

    /**
     * 获取管理端根路径
     */
    public static String getAdminPath() {
        return getConfig("adminPath");
    }

    /**
     * 获取前端根路径
     */
    public static String getFrontPath() {
        return getConfig("frontPath");
    }

    /**
     * 获取URL后缀
     */
    public static String getUrlSuffix() {
        return getConfig("urlSuffix");
    }

    /**
     * 是否是演示模式,演示模式下不能修改用户、角色、密码、菜单、授权
     */
    public static Boolean isDemoMode() {
        String dm = getConfig("demoMode");
        return "true".equals(dm) || "1".equals(dm);
    }

    /**
     * 在修改系统用户和角色时是否同步到Activiti
     */
    public static Boolean isSynActivitiIndetity() {
        String dm = getConfig("activiti.isSynActivitiIndetity");
        return "true".equals(dm) || "1".equals(dm);
    }

    /**
     * 页面获取常量
     * @see ${fns:getConst('YES')}
     */
    public static Object getConst(String field) {
        try {
            return Global.class.getField(field).get(null);
        } catch (Exception e) {
            // 异常代表无配置,这里什么也不做
        }
        return null;
    }

    /**
     * 获取上传文件的根目录
     * @return
     */
    public static String getUserfilesBaseDir() {
        String dir = getConfig("userfiles.basedir");
        if (StringUtils.isBlank(dir)){
            try {
                dir = ServletContextFactory.getServletContext().getRealPath("/");
            } catch (Exception e) {
                return "";
            }
        }
        if(!dir.endsWith("/")) {
            dir += "/";
        }
//      System.out.println("userfiles.basedir: " + dir);
        return dir;
    }

    /**
     * 获取工程路径
     * @return
     */
    public static String getProjectPath(){
        // 如果配置了工程路径,则直接返回,否则自动获取。
        String projectPath = Global.getConfig("projectPath");
        if (StringUtils.isNotBlank(projectPath)){
            return projectPath;
        }
        try {
            File file = new DefaultResourceLoader().getResource("").getFile();
            if (file != null){
                while(true){
                    File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
                    if (f == null || f.exists()){
                        break;
                    }
                    if (file.getParentFile() != null){
                        file = file.getParentFile();
                    }else{
                        break;
                    }
                }
                projectPath = file.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return projectPath;
    }

    /**
     * 写入properties信息
     * 
     * @param key
     *            名称
     * @param value
     *            值
     */
    public static void modifyConfig(String key, String value) {
        try {
            // 从输入流中读取属性列表(键和元素对)
            Properties prop = getProperties();
            prop.setProperty(key, value);
            String path = Global.class.getResource("/jeeplus.properties").getPath();
            FileOutputStream outputFile = new FileOutputStream(path);
            prop.store(outputFile, "modify");
            outputFile.close();
            outputFile.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回 Properties
     * @param fileName 文件名 (注意:加载的是src下的文件,如果在某个包下.请把包名加上)
     * @param 
     * @return
     */
    public static Properties getProperties(){
        Properties prop = new Properties();
        try {
            Reader reader = Resources.getResourceAsReader("/jeeplus.properties");
            prop.load(reader);
        } catch (Exception e) {
            return null;
        }
        return prop;
    }


}

全局配置文件

jeeplus.properties配置文件

#============================#
#===== Database sttings =====#
#============================#

#oracle database settings
#jdbc.type=oracle
#jdbc.driver=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:jeeplus
#jdbc.username=liugf
#jdbc.password=fnst1234

#mysql database setting
jdbc.type=mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.2.114:3306/jeeplus_schema?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

#mssql database settings
#jdbc.type=mssql
#jdbc.driver=net.sourceforge.jtds.jdbc.Driver
#jdbc.url=jdbc:jtds:sqlserver://localhost:1433/jeeplus
#jdbc.username=sa
#jdbc.password=sa

#pool settings
jdbc.pool.init=1
jdbc.pool.minIdle=3
jdbc.pool.maxActive=20

#jdbc.testSql=SELECT 'x'
jdbc.testSql=SELECT 'x' FROM DUAL

#redis settings
redis.keyPrefix=jeeplus
redis.host=127.0.0.1
redis.port=6379

#============================#
#===== System settings ======#
#============================#

#\u4ea7\u54c1\u4fe1\u606f\u8bbe\u7f6e
productName=JeePlus \u5feb\u901f\u5f00\u53d1\u5e73\u53f0
copyrightYear=2014
version=V1.2.6

#\u6f14\u793a\u6a21\u5f0f: \u4e0d\u80fd\u64cd\u4f5c\u548c\u4fdd\u5b58\u7684\u6a21\u5757\uff1a sys: area/office/user/role/menu/dict, cms: site/category
demoMode=false

#\u7ba1\u7406\u57fa\u7840\u8def\u5f84, \u9700\u540c\u6b65\u4fee\u6539\uff1aweb.xml
adminPath=/a

#\u524d\u7aef\u57fa\u7840\u8def\u5f84
frontPath=/f

#\u7f51\u7ad9URL\u540e\u7f00
urlSuffix=.html

#\u662f\u5426\u4e0d\u5141\u8bb8\u5237\u65b0\u4e3b\u9875\uff0c\u4e0d\u5141\u8bb8\u60c5\u51b5\u4e0b\uff0c\u5237\u65b0\u4e3b\u9875\u4f1a\u5bfc\u81f4\u91cd\u65b0\u767b\u5f55
notAllowRefreshIndex=false

#\u662f\u5426\u5141\u8bb8\u591a\u8d26\u53f7\u540c\u65f6\u767b\u5f55
user.multiAccountLogin=true

#\u5206\u9875\u914d\u7f6e
page.pageSize=10

#\u7855\u6b63\u7ec4\u4ef6\u662f\u5426\u4f7f\u7528\u7f13\u5b58
supcan.useCache=false

#\u901a\u77e5\u95f4\u9694\u65f6\u95f4\u8bbe\u7f6e, \u5355\u4f4d\uff1a\u6beb\u79d2, 30s=30000ms, 60s=60000ms
oa.notify.remind.interval=60000

#============================#
#==== Framework settings ====#
#============================#

#\u4f1a\u8bdd\u8d85\u65f6\uff0c \u5355\u4f4d\uff1a\u6beb\u79d2\uff0c 20m=1200000ms, 30m=1800000ms, 60m=3600000ms
session.sessionTimeout=1800000
#\u4f1a\u8bdd\u6e05\u7406\u95f4\u9694\u65f6\u95f4\uff0c \u5355\u4f4d\uff1a\u6beb\u79d2\uff0c2m=120000ms\u3002
session.sessionTimeoutClean=120000

#\u7f13\u5b58\u8bbe\u7f6e
ehcache.configFile=cache/ehcache-local.xml
#ehcache.configFile=cache/ehcache-rmi.xml

#\u7d22\u5f15\u9875\u8def\u5f84
web.view.index=/a

#\u89c6\u56fe\u6587\u4ef6\u5b58\u653e\u8def\u5f84
web.view.prefix=/webpage/
web.view.suffix=.jsp

#\u6700\u5927\u6587\u4ef6\u4e0a\u4f20\u9650\u5236\uff0c\u5355\u4f4d\u5b57\u8282. 10M=10*1024*1024(B)=10485760 bytes\uff0c\u9700\u540c\u6b65\u4fee\u6539\uff1ackfinder.xml
web.maxUploadSize=10485760

#\u65e5\u5fd7\u62e6\u622a\u8bbe\u7f6e\uff0c\u6392\u9664\u7684URI\uff1b\u5305\u542b @RequestMapping\u6ce8\u89e3\u7684value\u3002\uff08\u5df2\u4f5c\u5e9f\uff09
#web.logInterceptExcludeUri=/, /login, /sys/menu/tree, /sys/menu/treeData, /oa/oaNotify/self/count
#web.logInterceptIncludeRequestMapping=save, delete, import, updateSort

#\u9759\u6001\u6587\u4ef6\u540e\u7f00
web.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.htm,.html,.crx,.xpi,.exe,.ipa,.apk

#\u5355\u70b9\u767b\u5f55CAS\u8bbe\u7f6e
cas.server.url=http://127.0.0.1:8180/cas
cas.project.url=http://127.0.0.1:8080/jeeplus


#\u4e0a\u4f20\u6587\u4ef6\u7edd\u5bf9\u8def\u5f84, \u8def\u5f84\u4e2d\u4e0d\u5141\u8bb8\u5305\u542b\u201cuserfiles\u201d
#userfiles.basedir=D:/jeeplus

#\u5de5\u7a0b\u8def\u5f84\uff0c\u5728\u4ee3\u7801\u751f\u6210\u65f6\u83b7\u53d6\u4e0d\u5230\u5de5\u7a0b\u8def\u5f84\u65f6\uff0c\u53ef\u518d\u6b64\u6307\u5b9a\u7edd\u5bf9\u8def\u5f84\u3002
#projectPath=D\:\\workspace\\jeeplus

#
fromEmail=
toEmail=
emailName=
emailPassword=
cpu=100
jvm=100
ram=100

2,spring自带注入方法

  1. 配置文件内容
    这里写图片描述

  2. spring使用方法
    这里写图片描述

  3. spring加载配置文件
    这里写图片描述

Java项目,可以使用类来定义全局变量全局变量是指在整个项目都可以访问的变量。可以在一个类定义一个公共的静态变量,并通过类名来访问这个变量。例如,可以在一个名为Project的类添加全局变量: public class Project { public static String project_name; public static String project_softwaretype; public static String project_development; public static String project_language; public static String project_dataaddress; public static String project_timeunit; public static String project_datatype; } 在上述代码,通过在Project类定义公共静态变量,这些变量可以在整个项目通过类名Project来访问。可以使用类似以下的方式来给全局变量赋值: Project.project_name = "项目名称"; Project.project_softwaretype = "项目软件类型"; Project.project_development = "项目开发人员"; // 其他全局变量的赋值 通过这种方式,可以在Java项目添加全局变量。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [java实现整个工程全局变量的方法](https://blog.csdn.net/u012680593/article/details/47021801)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Python全局变量-全局变量命名的建议](https://download.csdn.net/download/WBFG888/85303557)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值