spring读取properties

合集下载

Spring加载Properties配置文件的三种方式

Spring加载Properties配置文件的三种方式

Spring加载Properties配置⽂件的三种⽅式⼀、通过 context:property-placeholder 标签实现配置⽂件加载1) ⽤法:1、在spring.xml配置⽂件中添加标签<context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>2、在 spring.xml 中使⽤配置⽂件属性:$<!-- 基本属性 url、user、password --><property name="url" value="${jdbc.url}"/><property name="username" value="${ername}"/><property name="password" value="${jdbc.password}" /3、在java⽂件中使⽤:@Value("${jdbc.url}")private String jdbcUrl; // 注意:这⾥变量不能定义成static2) 注意点:踩过的坑在Spring中的xml中使⽤<context:property-placeholderlocation>标签导⼊配置⽂件时,想要导⼊多个properties配置⽂件,如下:<context:property-placeholderlocation="classpath:db.properties " /><context:property-placeholderlocation="classpath:zxg.properties " />结果发现不⾏,第⼆个配置⽂件始终读取不到,Spring容器是采⽤反射扫描的发现机制,通过标签的命名空间实例化实例,当Spring探测到容器中有⼀个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停⽌对剩余PropertyPlaceholderConfigurer的扫描,即只能存在⼀个实例如果有多个配置⽂件可以使⽤ “,” 分隔<context:property-placeholderlocation="classpath:db.properties,classpath:monitor.properties"/>可以使⽤通配符 *<context:property-placeholderlocation="classpath:*.properties"/>3) 属性⽤法ignore-resource-not-found //如果属性⽂件找不到,是否忽略,默认false,即不忽略,找不到⽂件并不会抛出异常。

springboot获取properties属性值的多种方式总结

springboot获取properties属性值的多种方式总结

springboot获取properties属性值的多种⽅式总结⽬录获取properties属性值⽅式总结1. 除了默认配置在 application.properties的多环境中添加属性2. 使⽤之前在spring中加载的value值形式3. 也可以使⽤springboot⾥⾯的Environment 直接取值4. 如果是⾃⼰新建的⼀个properties⽂件获取多个⾃定义属性值⽐如在application中⾃定义属性获取properties属性值⽅式总结spring boot 在多环境情况下我们需要根据不同的获取不⼀样的值,我们会配置在不同的⽂件中,那么我们怎么获取配置的属性值呢!下⾯介绍⼏种⽤法。

1. 除了默认配置在 application.properties的多环境中添加属性我们会在application.properties 中激活不同⽅式选择下⾯的不同⽂件进⾏发布。

设置的激活参数:dev, test, prodspring.profiles.active=produrl.lm=editMessageCode=100120171116031838url.ybd=/sales/url.PostUrl=/LmCpa/apply/applyInfo获取属性可以, 定义配置类:@ConfigurationProperties(prefix = "url")public class ManyEnvProperties{private String lm;private String orgCode;private String ybd;private String postUrl;// 省列getter setter ⽅法}2. 使⽤之前在spring中加载的value值形式@Componentpublic class ManyEnvProperties {@Value("${url.lm}")private String lmPage;@Value("${url.ybd}")private String sendYbdUrl;@Value("${Code}")private String orgCode;@Value("${url.PostUrl}")private String PostUrl;// 省列getter setter ⽅法}3. 也可以使⽤springboot⾥⾯的Environment 直接取值显⽰注⼊,其次是在需要的地⽅获取值@Autowiredprivate Environment env;("===============》 " + env.getProperty("url.lm"));4. 如果是⾃⼰新建的⼀个properties⽂件@Component@ConfigurationProperties(prefix = "url")@PropertySource("classpath:/platform.properties")public class PropertiesEnv {private String lm;private String orgCode;private String ybd;private String postUrl;// 省列getter setter ⽅法}获取多个⾃定义属性值使⽤@Value 注⼊每个⾃定义配置,当⾃定义配置的属性值过多时就⽐较⿇烦了,这时通过springboot提供了基于类型安全的配置⽅法,通过@ConfigurationProperties将properties中的属性和⼀个bean的属性关联,从⽽实现类型安全的配置,⽐如在application中⾃定义属性note.author=yzh=china可以通过@ConfigurationProperties(prefix="note")需要注意的是⾃定义属性值的前缀统⼀为note才可以获取到对应的属性值.属性值名称要跟配置⽂件⾥⾯的名称对应起来同时通过这种⽅法需要⽣成属性值的get/set ⽅法,否则获取不到对应的属性值以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

springboot如何读取自定义properties并注入到bean中

springboot如何读取自定义properties并注入到bean中

springboot如何读取⾃定义properties并注⼊到bean中⽬录读取⾃定义properties注⼊到beanspringboot启动⽇志如下springboot bean实例化和属性注⼊过程springboot版本(2.0.4 RELEASE)Bean的实例化Bean的属性注⼊读取⾃定义properties注⼊到bean在使⽤springboot项⽬时,可使⽤@value的⽅式直接读取application.properties中的⽂件,但有时我们需要配置⾃定义的properties,下⾯⽅法将在springboot启动时利⽤fileinputstream读取properties⽂件中的内容,并注⼊到bean中,@Configuration注解会在springboot启动时执⾏⼀次,代码如下:package com.shanqis.parking.properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import java.util.Properties;/*** 读取resource下的.properties⽂件,将⽂件中的内容封装到map中,注⼊到bean中⽅便依赖注⼊** @author Administrator*/@Configurationpublic class PropertiesClassLoader {private Logger logger = LoggerFactory.getLogger(PropertiesClassLoader.class);private Map<String, Object> versionProperties = new HashMap<>(16);private void init(String name) {try {Properties properties = new Properties();InputStream in = PropertiesClassLoader.class.getClassLoader().getResourceAsStream(name + ".properties");properties.load(in);("加载{}.properties参数", name);for (String keyName : properties.stringPropertyNames()) {String value = properties.getProperty(keyName);if ("version".equals(name)) {versionProperties.put(keyName, value);}("{}.properties---------key:{},value:{}", name, keyName, value);}("{}.properties参数加载完毕", name);} catch (IOException ignored) {}}@Bean(name = "versionProperties")public Map<String, Object> commonMap() {init("version");return versionProperties;}}springboot启动⽇志如下然后在controller层或者service层等可以这样使⽤/*** 读取common.properties⽂件*/@Autowired @Qualifier("commonMap")protected Map<String, String> commonMap;springboot bean实例化和属性注⼊过程springboot版本(2.0.4 RELEASE)⼤致描述springboot中bean的实例化和属性注⼊过程流程1)在某⼀时刻Spring调⽤了Bean⼯⼚的getBean(beanName)⽅法。

Spring框架读取property属性文件常用5种方法

Spring框架读取property属性文件常用5种方法

Spring框架读取property属性⽂件常⽤5种⽅法1、⽅式⼀:通过spring框架 PropertyPlaceholderConfigurer ⼯具实现<bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="locations"><value>classpath:conf/jdbc.properties</value></property><property name="fileEncoding"><value>UTF-8</value></property><property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /></bean><!-- 数据源配置 --><bean id="dataSource" class="mons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${database.connection.driver}"/><property name="url" value="${database.connection.url}"/><property name="username" value="${ername}"/><property name="password" value="${database.connection.password}"/></bean><!-- DAL客户端接⼝实现-><bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean>2、⽅式⼆:简化配置<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:jee="/schema/jee" xmlns:aop="/schema/aop"xmlns:context="/schema/context" xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd/schema/jee /schema/jee/spring-jee.xsd/schema/context /schema/context/spring-context.xsd/schema/aop /schema/aop/spring-aop.xsd/schema/tx /schema/tx/spring-tx.xsd"><context:property-placeholder location="classpath:conf/jdbc.properties" ignore-unresolvable="true"/><!-- 数据源配置 --><bean id="dataSource" class="mons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${database.connection.driver}"/><property name="url" value="${database.connection.url}"/><property name="username" value="${ername}"/><property name="password" value="${database.connection.password}"/></bean><!-- DAL客户端接⼝实现--><bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><!--备注:如果${} 这种写法⽆法读取到,或者编译出错,则增加ignore-unresolvable="true"的属性信息,并添加上⽂的命名空间信息-->jdbc.properties⽂件:database.connection.driver=com.mysql.jdbc.Driverdatabase.connection.url=jdbc:mysql://*.*.*.*:3306/mysql?characterEncoding=utf-8ername=*database.connection.password=*上述配置理解:1)ignore-unresolvable属性的⽰意:<xsd:documentation><![CDATA[Specifies if failure to find the property value to replace a key should be ignored.Default is "false", meaning that this placeholder configurer will raise an exceptionif it cannot resolve a key. Set to "true" to allow the configurer to pass on the keyto any others in the context that have not yet visited the key in question.]]>翻译后:指定是否应忽略未能找到⽤于替换键的属性值。

关于properties文件的读取(Javaspringspringmvcspringboot)

关于properties文件的读取(Javaspringspringmvcspringboot)

关于properties⽂件的读取(Javaspringspringmvcspringboot)⼀.Java读取properties⽂件1、基于ClassLoder读取配置⽂件注意:该⽅式只能读取类路径下的配置⽂件,有局限但是如果配置⽂件在类路径下⽐较⽅便。

1 Properties properties = new Properties();2// 使⽤ClassLoader加载properties配置⽂件⽣成对应的输⼊流3 InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");4// 使⽤properties对象加载输⼊流5 properties.load(in);6//获取key对应的value值7 properties.getProperty(String key);2、基于 InputStream 读取配置⽂件注意:该⽅式的优点在于可以读取任意路径下的配置⽂件1 Properties properties = new Properties();23// 使⽤InPutStream流读取properties⽂件45 BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));67 properties.load(bufferedReader);89// 获取key对应的value值properties.getProperty(String key);3、通过 java.util.ResourceBundle 类来读取,这种⽅式⽐使⽤ Properties 要⽅便⼀些 1>通过 ResourceBundle.getBundle() 静态⽅法来获取(ResourceBundle是⼀个抽象类),这种⽅式来获取properties属性⽂件不需要加.properties后缀名,只需要⽂件名即可1 properties.getProperty(String key);2//config为属性⽂件名,放在包com.test.config下,如果是放在src下,直接⽤config即可3 ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");4 String key = resource.getString("keyWord"); 2>从 InputStream 中读取,获取 InputStream 的⽅法和上⾯⼀样,不再赘述1 ResourceBundle resource = new PropertyResourceBundle(inStream);注意:在使⽤中遇到的最⼤的问题可能是配置⽂件的路径问题,如果配置⽂件⼊在当前类所在的包下,那么需要使⽤包名限定,如:config.properties⼊在com.test.config包下,则要使⽤com/test/config/config.properties(通过Properties来获取)或com/test/config/config(通过ResourceBundle来获取);属性⽂件在src根⽬录下,则直接使⽤config.properties或config即可。

Spring读取Properties配置文件

Spring读取Properties配置文件

Spring读取Properties配置⽂件 ⼀、application.properties 配置⽂件 ①:⽤Spring容器获取Environment变量,然后getProperty获取到配置的value ConfigurableEnvironment environment = context.getEnvironment();  String name = environment.getProperty("name"); ②:@Value注解 使⽤@Value("${key}" ③:@ConfigurationProperties @ConfigurationProperties注解有⼀个prefix属性,通过指定的前缀,绑定配置⽂件中的配置,如:@Component@ConfigurationProperties(prefix = "global.jdbc")public class GlobalProperties {private String url;private String driver;private String username;private String password;...getter/setter} ⼆、⾃定义properties 配置⽂件 ①:@PropertySource + @Value("${key}") @PropertySource :使⽤@PropertySource读取外部配置⽂件中的k/v保存到运⾏的环境变量Environment中; 如:@PropertySource("classpath:mysql.properties") 取值⽅式: ①:使⽤@Value("${key}" ②:也可以⽤Spring容器获取Environment变量,然后getProperty获取到配置的value ConfigurableEnvironment environment = context.getEnvironment();  String name = environment.getProperty("name"); ②:⾃⾏直接读取配置⽂件的值并缓存public class PropertiesUtil {private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);private PropertiesUtil() {}private static final Properties PROPERTIES = readProperties("config.properties", "talos.properties");private static Properties readProperties(String... confFile) {final Properties properties = new Properties();try {for (String path : confFile) {final ClassPathResource resource = new ClassPathResource(path);properties.load(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));}} catch (IOException e) {LOGGER.error(e.getMessage(), e);}return properties;}public static String get(String key) {return PROPERTIES.getProperty(key); }}END.。

SPRINGBOOT读取PROPERTIES配置文件数据过程详解

SPRINGBOOT读取PROPERTIES配置文件数据过程详解

SPRINGBOOT读取PROPERTIES配置文件数据过程详解
Spring Boot读取properties配置文件的过程可以通过下面的步骤
来详解:
1. 创建配置文件:首先,在Spring Boot项目的resources目录下
创建一个新的配置文件,可以是application.properties或者自定义的
文件名,例如custom.properties。

在配置文件中,可以设置任意的属性
和对应的值。

例如,可以设置数据库连接信息、日志配置、端口号等。

2. 加载配置文件:Spring Boot会自动加载并解析配置文件。

它会
并加载资源目录下的所有properties文件,并将属性值加载到属性映射中。

5.使用配置值:一旦属性值被注入到类中,就可以通过类的字段来访
问配置值。

然后,可以在需要使用配置值的地方,直接使用对应的字段即可。

6. 配置文件的优先级:在Spring Boot中,配置文件的优先级是由
低到高的,高优先级的配置会覆盖低优先级的配置。

优先级从低到高依次为:默认的配置文件(application.properties或application.yml)<
自定义的配置文件(如custom.properties)<命令行参数。

总的来说,Spring Boot读取properties配置文件的过程包括创建
配置文件、加载配置文件、创建配置类、注入配置值、使用配置值等步骤。

通过这些步骤,可以方便地使用配置文件中的属性值,并实现动态刷新配置。

Spring中属性文件properties的读取与使用详解

Spring中属性文件properties的读取与使用详解

Spring中属性⽂件properties的读取与使⽤详解Spring中属性⽂件properties的读取与使⽤详解实际项⽬中,通常将⼀些可配置的定制信息放到属性⽂件中(如数据库连接信息,邮件发送配置信息等),便于统⼀配置管理。

例中将需配置的属性信息放在属性⽂件/WEB-INF/configInfo.properties中。

其中部分配置信息(邮件发送相关):#邮件发送的相关配置email.host = email.port = xxxername = xxxemail.password = xxxemail.sendFrom=***********在Spring容器启动时,使⽤内置bean对属性⽂件信息进⾏加载,在bean.xml中添加如下:Xml代码<!-- spring的属性加载器,加载properties⽂件中的属性 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>/WEB-INF/configInfo.properties</value></property><property name="fileEncoding" value="utf-8" /></bean>属性信息加载后其中⼀种使⽤⽅式是在其它bean定义中直接根据属性信息的key引⽤value,如邮件发送器bean的配置如下:Xml代码<!-- 邮件发送 --><bean id="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host"><value>${email.host}</value></property><property name="port"><value>${email.port}</value></property><property name="username"><value>${ername}</value></property><property name="password"><value>${email.password}</value></property><property name="javaMailProperties"><props><prop key="mail.smtp.auth">true</prop><prop key="sendFrom">${email.sendFrom}</prop></props></property></bean>另⼀种使⽤⽅式是在代码中获取配置的属性信息,可定义⼀个javabean:ConfigInfo.java,利⽤注解将代码中需要使⽤的属性信息注⼊;如属性⽂件中有如下信息需在代码中获取使⽤:Java代码#⽣成⽂件的保存路径file.savePath = D:/test/#⽣成⽂件的备份路径,使⽤后将对应⽂件移到该⽬录file.backupPath = D:/test bak/ConfigInfo.java 中对应代码:Java代码@Component("configInfo")public class ConfigInfo {@Value("${file.savePath}")private String fileSavePath;@Value("${file.backupPath}")private String fileBakPath;public String getFileSavePath() {return fileSavePath;}public String getFileBakPath() {return fileBakPath;}}业务类bo中使⽤注解注⼊ConfigInfo对象:Java代码@Autowiredprivate ConfigInfo configInfo;需在bean.xml中添加组件扫描器,⽤于注解⽅式的⾃动注⼊:Xml代码<context:component-scan base-package="com.my.model" />(上述包model中包含了ConfigInfo类)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

spring 框架的xml文件如何读取properties文件数据
第一步:在spring配置文件中
注意:value可以多配置几个properties文件
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/db.properties</value>
</list>
</property>
</bean>
第二步:
在src目录下面建立db.properties文件
user=sa
password=sa
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=DB1
第三步:
在spring的配置文件中通过EL表达式的形式调用
${user}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans-2.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/db.properties</value>
</list>
</property>
</bean>
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${driver}">
</property>
<property name="url"
value="${url}">
</property>
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property> </bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="datasource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>entity/Users.hbm.xml</value>
</list>
</property>
</bean>
<bean id="UsersDAO" class="ersDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>。

相关文档
最新文档