怎么在spring配置文件中配置properties

怎么在spring配置文件中配置properties

本文目录

  • 怎么在spring配置文件中配置properties
  • 怎么使用C语言读取properties配置文件
  • db.properties配置文件在哪里配置,第一步怎么做
  • 如何读取.properties文件配置的两种方法
  • 怎样在.properties文件中注释
  • 如何从Properties配置文件读取值
  • properties是什么文件
  • 如何在spring中读取properties配置文件里面的信息
  • springboot application.properties 写多个配置文件怎么写

怎么在spring配置文件中配置properties


1.PropertyPlaceholderConfigurer类
它是把属性中的定义的变量(var)替代,spring的配置文件中使用${var}的占位符
《beans》
《bean id=“configBean“ class=“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer“》
《property name=“location“》《value》db.properties《/value》《/property》
《/bean》
《bean id=“dataSource“ class=“org.apache.commons.dbcp.BasicDataSource“ destroy-method=“close“》
《property name=“driverClassName“》《value》${jdbc.driverClassName}《/value》《/property》
《property name=“url“》《value》${jdbc.url}《/value》《/property》
《property name=“username“》《value》${jdbc.username}《/value》《/property》
《property name=“password“》《value》${jdbc.password}《/value》《/property》
《/bean》
《/beans》
db.properties文件
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
2.PropertyOverrideConfigurer类
跟PropertyPlaceholderConfigurer功能一样,不过用法不一样.不用占位符,在属性文件中
直接定义属性的值,这样就允许有默认
《beans》
《bean id=“configBean“ class=“org.springframework.beans.factory.config.PropertyOverrideConfigurer“》
《property name=“location“》《value》db.properties《/value》《/property》
《/bean》
《bean id=“dataSource“ class=“org.apache.common

怎么使用C语言读取properties配置文件


用C语言读取properties配置文件的方法:
1、找到配置路径下的properties文件
2、按行读取文件内容
具体实现代码如下:
//定义读入的行数组,1024行
char line;
//存放配置项数组setting
int setting[N],i = 0;
//开始循环读入
while(fgets(fp,line,1024) != NULL)
{
//读入配置的值给line变量
fscanf(line,“setting%*d = %d“,&setting[i++]);
}

db.properties配置文件在哪里配置,第一步怎么做


db.properties连接池的用法Properties文件,其实仅仅是键值对配置文件。下面介绍如何读取properties文件以及如何用JDBC连接数据库。 1.[读取配置文件]: 比如你的properties文件叫做mysql.properties,并且放在com.test包下: java.net.URL url = Thread.currentThread().getContextClassLoader().getResource(“com/test/mysql.properties“); 注意路径和包名一致,在你的提问中,我们知道是放在classes目录下,则直接 ...getResource(“mysql.properties“); 即可 Properties p = new Properties(); p.load(url.openStream()); //由URL载入配置文件 这样你就得到一个Properties的实例 2. [读取配置文件信息]: 比如你要读取drivers的值,只需: String theDriver = p.get(“drivers“); 根据配置文件,这样你就得到了“org.gjt.mm.mysql.Driver“ 3.[利用JDBC连接数据库] 首先你要保证你有MySQL的Jdbc驱动程序,即包含org.gjt.mm.mysql.Driver的jar包,并放在应用的classpath里。你可以搜索一下,很多地方有下的: mysql-connector-java-3.0.15-ga-bin.jar 然后用同样的方法得到url, mysql.user, mysql.password的值,比如分别为 url, user, pass 然后建立连接: Class.forName(“com.mysql.jdbc.Driver“); java.sql.Connection conn = java.sql.DriverManager.getConnection(url, user, pass); 如果不出意外,你就得到连接数据库的Connection了,注意用完了别忘了关啊。(conn.close();) 4.[补充说明] properties文件只是一个键-值对的配置文件(而且键和值都是可以自己写的,并没有固定格式,要看程序需求),从它“本身”只能得到键对应的值。具体这个值用来干什么,那是程序的事情。比如logfile和maxconn,我只能猜是用来处理log和建立连接池时标记最大连接数的,具体怎么实现,需要研究它的代码,因为并没有固定写法。(而上面用jdbc建立连接的写法是固定的)。因为你只给了个properties文件,所以我只能写一个jdbc的连接程序,但这并不是连接池的实现。 这里有个连接池的实现,你可以参考下: 3 .Java数据库连接池的实现 连接池的配置文件--db.properties(放置在classes目录下) 19:52drivers=sun.jdbc.odbc.JdbcOdbcDriverlogfile=c:/dbpool.log.txtCOMDB.url=jdbc:odbc:COMDBCOMDB.user=AdminCOMDB.password=123456COMDB.initconns=5COMDB.maxconns=50COMDB.logintimeout=5COMDB.loglevel=infoattend.url=jdbc:odbc:attendattend.user=userattend.password=1234attend.initconns=5attend.maxconns=50attend.logintimeout=5attend.loglevel=info

如何读取.properties文件配置的两种方法


[html] view plain copy print?
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.util.Properties;  
  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.core.io.DefaultResourceLoader;  
import org.springframework.core.io.Resource;  
import org.springframework.core.io.ResourceLoader;  
import org.springframework.util.DefaultPropertiesPersister;  
import org.springframework.util.PropertiesPersister;  
  
/**  
 * Properties Util函数.  
 *   
 * @author uniz  
 */  
public class PropertiesUtils {  
  
    private static final String DEFAULT_ENCODING = “UTF-8“;  
  
    private static Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);  
  
    private static PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();  
    private static ResourceLoader resourceLoader = new DefaultResourceLoader();  
  
    /**  
     * 载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的载入.  
     * 文件路径使用Spring Resource格式, 文件编码使用UTF-8.  
     *   
     * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  
     */  
    public static Properties loadProperties(String... resourcesPaths) throws IOException {  
        Properties props = new Properties();  
  
        for (String location : resourcesPaths) {  
  
            logger.debug(“Loading properties file from:“ + location);  
  
            InputStream is = null;  
            try {  
                Resource resource = resourceLoader.getResource(location);  
                is = resource.getInputStream();  
                propertiesPersister.load(props, new InputStreamReader(is, DEFAULT_ENCODING));  
            } catch (IOException ex) {  
                logger.info(“Could not load properties from classpath:“ + location + “: “ + ex.getMessage());  
            } finally {  
                if (is != null) {  
                    is.close();  
                }  
            }  
        }  
        return props;  
    }  
      
    public static String getDataVal(String key) {  
        try {  
            Properties properties = PropertiesUtils.loadProperties(“/config/config.properties“);  
            if (properties == null) return ““;  
          
            return new String((properties.getProperty(key))  
                    .getBytes(“ISO8859_1“), “utf-8“);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
}  
[html] view plain copy print?
   
[html] view plain copy print?

怎样在.properties文件中注释


1、打开IDEA,新建一个Web项目,右键点击新建的项目名,选择创建文件目录(Directory),一般properties文件夹命名应为resoures。

2、右键点击新建的resources文件夹,弹出的窗口里选择Mark Dictory as 》》Resources Root将文件夹定义为配置文件。

3、也可以通过Ctrl+shift+alt+s组合件打开Project Structure面板将需要的文件夹声明为配置文件类型

4、右键点击声明为resources类型的文件夹选择Resource Bundle,就能创架一个properties文件了。

5、mysql 的properties配置文件是以键值对形式存读取的,一个对象占用一行,行末不能添加分号。

6、配置文件的使用。就可以注释了。


如何从Properties配置文件读取值


最常用读取properties文件的方法
InputStream in = getClass().getResourceAsStream(“资源Name“);这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:
InputStream ins = this.getClass().getResourceAsStream(“/cn/zhao/properties/testPropertiesPath3.properties“);
Java中获取路径方法
获取路径的一个简单实现
反射方式获取properties文件的三种方式
1 反射方式获取properties文件最常用方法以及思考:
Java读取properties文件的方法比较多,网上最多的文章是“Java读取properties文件的六种方法“,但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:
InputStream in = getClass().getResourceAsStream(“资源Name“);
这里面有个问题,就是getClass()调用的时候默认省略了this!我们都知道,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。
问题是:假如我不想让某个类有对象,那么我会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。并且我这个类是工具类,都是静态的方法和变量,我要在静态块或者静态方法中获取properties文件,这个方法就行不通了。
那怎么办呢?其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那还不容易啊--
取所有类的父类Object,用Object.class难道不比你的用你正在写类自身方便安全吗 ?呵呵,下面给出一个例子,以方便交流。
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
/**
* 读取Properties文件的例子
* File: TestProperties.java
* User: leizhimin
* Date: 2008-2-15 18:38:40
*/
public final class TestProperties {
private static String param1;
private static String param2;
static {
Properties prop = new Properties();
InputStream in = Object. class .getResourceAsStream( “/test.properties“ );
try {
prop.load(in);
param1 = prop.getProperty( “initYears1“ ).trim();
param2 = prop.getProperty( “initYears2“ ).trim();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 私有构造方法,不需要创建对象
*/
private TestProperties() {
}
public static String getParam1() {
return param1;
}
public static String getParam2() {
return param2;
}
public static void main(String args){
System.out.println(getParam1());
System.out.println(getParam2());
}
}
运行结果:
151
152
当然,把Object.class换成int.class照样行,呵呵,大家可以试试。
另外,如果是static方法或块中读取Properties文件,还有一种最保险的方法,就是这个类的本身名字来直接获取Class对象,比如本例中可写成TestProperties.class,这样做是最保险的方法
2 获取路径的方式:
File fileB = new File( this .getClass().getResource( ““ ).getPath());
System. out .println( “fileB path: “ + fileB);
2.2获取当前类所在的工程名:
System. out .println(“user.dir path: “ + System. getProperty (“user.dir“))《span style=“background-color: white;“》3 获取路径的一个简单的Java实现《/span》
/**

properties是什么文件


那是一种属性文件。
这种文件以key=value格式存储内容
代码中可以使用Properties类来读取这个文件
String value=p.getProperty(key);
就能得到对应的数据
一般这个文件作为一些参数的存储,代码就可以灵活一点
用于适应多语言环境,随着系统的语言环境的变化,读取不同的属性文件,显示对应语言的UI
当配置文件用,在里面读取一些关于路径方面的设置(如ant中的build.properties)
存放一组配置.(类似win下ini, 还要简单些, 因为没有section)
由于难以表达层次, 复杂点可以用xml做配置.
通俗点讲就相当于定义一个变量,在这个文件里面定义这些变量的值,在程序里面可以调用这些变量,好处就是,如果程序中的参数值需要变动,直接来改这个.property文件就可以了,不用在去修改源代码。
优点在于有利于你以后的代码重构,维护方便

如何在spring中读取properties配置文件里面的信息


一般来说。我们会将一些配置的信息放在。properties文件中。 然后使用${}将配置文件中的信息读取至spring的配置文件。 那么我们如何在spring读取properties文件呢。 1.首先。我们要先在spring配置文件中。定义一个专门读取properties文件的类. 例: 《bean id=“propertyConfigurer“ class=“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer“》 《property name=“locations“》 《list》 《value》classpath*:jdbc.properties《/value》 《!--要是有多个配置文件,只需在这里继续添加即可 --》 《/list》 《/property》 《/bean》 这里为什么用locations(还有一个location) 是因为。一般来说。我们的项目里面。配置文件可能存在多个。 就算是只有一个。那将来新添加的话。只需在下面再加一个value标签即可。 而不必再重新改动太多。(当然。性能上是否有影响,这个以当前这种服务器的配置来说。是基科可以忽略不计的)。 然后我们就可以在jdbc.properties文件中填写具体的配置信息了。 《!-- 配置C3P0数据源 --》 《bean id=“dataSource“ class=“com.mchange.v2.c3p0.ComboPooledDataSource“ destroy-method=“close“》 《property name=“driverClass“》 《value》${jdbc.driverClassName}《/value》 《/property》 《property name=“jdbcUrl“》 《value》${jdbc.url}《/value》 《/property》 《property name=“user“》 《value》${jdbc.username}《/value》 《/property》 《property name=“password“》 《value》${jdbc.password}《/value》 《/property》 《/bean》 jdbc.properties文件写的信息。 jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root 附加一个列子:   《bean class=“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer“》 《property name=“locations“》 《list》 《value》file:/data/pc-config/passport.properties《/value》 《value》classpath:memcached.properties《/value》 《/list》 《/property》 《/bean》   classpath:是指的当前类文件的目录下。   file:在window下是指的当前分区(比如你的项目是放在d盘,则是在d:/data/pc-config/passport.properties)   在linux下,则是当前路径下的文件/data/pc-config/passport.properties 转载仅供参考,版权属于原作者。祝你愉快,满意请~~哦

springboot application.properties 写多个配置文件怎么写


springboot application.properties 写多个配置文件的方法:

# 文件编码

banner.charset= UTF-8

# 文件位置

banner.location= classpath:banner.txt

# 日志配置

# 日志配置文件的位置。 例如对于Logback的`classpath:logback.xml`

logging.config= 

# %wEx#记录异常时使用的转换字。

logging.exception-conversion-word= 

# 日志文件名。 例如`myapp.log`

logging.file= 

# 日志级别严重性映射。 例如`logging.level.org.springframework =  DEBUG`

logging.level.*= 

# 日志文件的位置。 例如`/ var / log

logging.path= 

# 用于输出到控制台的Appender模式。 只支持默认的logback设置。

logging.pattern.console=

# 用于输出到文件的Appender模式。 只支持默认的logback设置。

logging.pattern.file= 

# 日志级别的Appender模式(默认%5p)。 只支持默认的logback设置。

logging.pattern.level=

#注册日志记录系统的初始化挂钩。

logging.register-shutdown-hook= false

# AOP 切面

# 添加@EnableAspectJAutoProxy。

spring.aop.auto= true

# 是否要创建基于子类(CGLIB)的代理(true),而不是基于标准的基于Java接口的代理(false)。

spring.aop.proxy-target-class= false

# 应用程序上下文初始化器

# 应用指标。

spring.application.index= 

# 应用程序名称。

spring.application.name= 
# 国际化(消息源自动配置)
#
spring.messages.basename= messages

# 以逗号分隔的基础名称列表,每个都在ResourceBundle约定之后。

# 加载的资源束文件缓存到期,以秒为单位。 设置为-1时,软件包将永久缓存。

spring.messages.cache-seconds= -1

# 消息编码。

spring.messages.encoding= UTF-8

# 设置是否返回到系统区域设置,如果没有找到特定语言环境的文件。

spring.messages.fallback-to-system-locale= true

# REDIS (Redis 配置)

# 连接工厂使用的数据库索引。

spring.redis.database= 0

# Redis服务器主机。

spring.redis.host= localhost

# 登录redis服务器的密码

spring.redis.password= 

# 给定时间池可以分配的最大连接数。 使用负值为无限制。

spring.redis.pool.max-active= 8

# 池中“空闲”连接的最大数量。 使用负值来表示无限数量的空闲连接。

spring.redis.pool.max-idle= 8

# 连接分配在池耗尽之前在抛出异常之前应阻止的最大时间量(以毫秒为单位)。 使用负值无限期地阻止。

spring.redis.pool.max-wait= -1

# 定义池中维护的最小空闲连接数。 此设置只有在正值时才有效果。

spring.redis.pool.min-idle= 0

# redis服务器端口

spring.redis.port= 6379

# redis服务器名称

spring.redis.sentinel.master=

# spring.redis.sentinel.nodes= 

# 连接超时(毫秒)。

spring.redis.timeout= 0

# 管理员 (Spring应用程序管理员JMX自动配置)

# 开启应用管理功能。

spring.application.admin.enabled= false

# JMX应用程序名称MBean。

spring.application.admin.jmx-name= org.springframework.boot:type= Admin,name= SpringApplication

# 自动配置

# 自动配置类排除。

spring.autoconfigure.exclude= 

# spring 核心配置

# 跳过搜索BeanInfo类。

spring.beaninfo.ignore= true

# spring 缓存配置

# 由底层缓存管理器支持的要创建的缓存名称的逗号分隔列表。

spring.cache.cache-names= 

# 用于初始化EhCache的配置文件的位置。

spring.cache.ehcache.config= 

# 用于创建缓存的规范。 检查CacheBuilderSpec有关规格格式的更多细节。

spring.cache.guava.spec= 

# 用于初始化Hazelcast的配置文件的位置。

spring.cache.hazelcast.config= 

# 用于初始化Infinispan的配置文件的位置。

spring.cache.infinispan.config= 

# 用于初始化缓存管理器的配置文件的位置。

spring.cache.jcache.config= 

# 用于检索符合JSR-107的缓存管理器的CachingProvider实现的完全限定名称。 只有在类路径上有多个JSR-107实现可用时才需要。

spring.cache.jcache.provider= 

# 缓存类型,默认情况下根据环境自动检测

spring.cache.type= 

# spring配置 (配置文件应用侦听器)

# 配置文件位置。

spring.config.location= 

# 配置文件名。

spring.config.name= application

Springboot的多配置文件是指:系统中存在多个配置文件,在不同的运行环境使用不同的配置文件即可。

启动项目的方法一般有两种 :

1、 运行RootApplication中的main方法。

2、 使用命令:mvn spring-boot:run

这两方法默认都是使用application.properties中的配置信息,如果有指spring.profiles.active则使用指定的配置信息,这种方式一般用在产品运行时,在开发和测试的时候则需要指定配置文件。


免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部