spring properties的配置与使用

本文详细介绍了Spring框架中配置PropertyPlaceholderConfigurer的方法,包括XML配置文件中自动替换变量的方式、使用@Value注解注入配置值以及通过Properties类加载配置文件的示例,并展示了Spring Boot环境下配置文件的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring
配置

PropertyPlaceholderConfigurer

<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="fileEncoding" value="utf-8"/>
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:${env}/important.properties</value>
            <value>classpath:${env}/sys.properties</value>
        </list>
    </property>

</bean>

也可以如下两种形式:
Context

<!-- spring命名空间 -->
http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-4.0.xsd
<context:property-placeholder location="classpath:packagename/*.properties" />           

util

<!-- spring命名空间 -->
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
<util:properties id="config" location="classpath:packagename/config.properties"/>
<!-- 使用如下:例 mysql.driverClassName -->
<bean id="client" class="com.package.businessname.service.impl.XXXServiceImpl">
        <constructor-arg index="0" value="#{config['properties.keyName']}"/> 
</bean>        
使用
  • 在 xml 配置文件中使用
    即自动替换 ${} 里面的值。
<property name="username" value="${pip.jdbc.username}" />
  • 通过 @Value 注入使用
@Value("${pip.jdbc.username}")
private String username;
  • -
Properties prop = new Properties();
InputStream inStream = ConfigLoader.class.getClassLoader().getResourceAsStream("common.properties");
prop.load(inStream);
username= Long.parseLong(prop.getProperty("pip.jdbc.username"));
spring boot

每个项目都默认有一个 application.properties 文件,这个配置文件不需要像前面说的那样进行注册,Spring Boot 会帮我们自动注册。

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=1qaz2wsx

为了给不同的环境指定不同的配置,我们可以作如下配置

application-{env}.properties

启动时,则执行如下
java -Dspring.profiles.active={env} -jar app.jar

java文件,如下:

@Configuration
//自动在 Spring 的容器注册一个类型为 DataSource 的 javabean ,且属性都已经 set 过
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSource {
    String url;
    String username;
    String password;
    // getters and setters
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值