PropertiesFactoryBean 和PreferencesPlaceholderConfigurer 使用properties配置

详解Spring通过@Value注解注入属性的几种方式 本篇文章主要介绍了详解Spring通过@Value注解注入属性的几种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。 立即下载

转载 http://outofmemory.cn/code-snippet/3700/spring-bean-property-inject


在很多情况下我们需要在配置文件中配置一些属性,然后注入到bean中,Spring提供了org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer类,可以方便我们使用注解直接注入properties文件中的配置。

下面我们看下具体如何操作:

首先要新建maven项目,并在pom文件中添加spring依赖,如下pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.outofmemory</groupId>
  <artifactId>hellospring.properties.annotation</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>hellospring.properties.annotation</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework-version>3.0.0.RC2</org.springframework-version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>              
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
  </dependencies>
</project>

要自动注入properties文件中的配置,需要在spring配置文件中添加org.springframework.beans.factory.config.PropertiesFactoryBean和org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer的实例配置:

如下spring配置文件appContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
    <!-- bean annotation driven -->
    <context:annotation-config />
    <context:component-scan base-package="cn.outofmemory.hellospring.properties.annotation">
    </context:component-scan>
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath*:application.properties</value>
            </list>
        </property>
    </bean>
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>    
</beans>

在这个配置文件中我们配置了注解扫描,和configProperties实例和propertyConfigurer实例。这样我们就可以在java类中自动注入配置了,我们看下java类中如何做:

package cn.outofmemory.hellospring.properties.annotation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MySQLConnectionInfo {

    @Value("#{configProperties['mysql.url']}")
    private String url;
    @Value("#{configProperties['mysql.userName']}")
    private String userName;
    @Value("#{configProperties['mysql.password']}")
    private String password;

    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
}

自动注入需要使用@Value注解,这个注解的格式#{configProperties['mysql.url']}其中configProperties是我们在appContext.xml中配置的beanId,mysql.url是在properties文件中的配置项。

properties文件的内容如下:

mysql.url=mysql's url
mysql.userName=mysqlUser
mysql.password=mysqlPassword

最后我们需要测试一下以上写法是否有问题,如下App.java文件内容:

package cn.outofmemory.hellospring.properties.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");
        MySQLConnectionInfo connInfo = appContext.getBean(MySQLConnectionInfo.class);
        System.out.println(connInfo.getUrl());
        System.out.println(connInfo.getUserName());
        System.out.println(connInfo.getPassword());
    }
}

在main方法中首先声明了appContext,然后获得了自动注入的MySQLConnectionInfo的实例,然后打印出来,运行程序会输出配置文件中配置的值。


74HC138译码器的原理和使用 A0,A1,A2为3位二进制加权地址输入端口,A2A1A0顺序组成的3位2进制数对应的十进制数x控制使能端口Yx';例如当A2A1A0 = 101 时,其他门输出端全为高电平,只有Y5'为低电平。 Y0-Y7为8个输出端口,其输出电平由A0,A2,A3,E1,E2,E3决定。 阅读详情

相关推荐

【 史上最全】测绘、遥感RS、地信GIS国家级比赛竞赛整理

目录Esri Esri

weixin_43910227的博客 9150

Spring 依赖注入:自动注入properties文件中的配置

在很多情况下我们需要在配置文件中配置一些属性,然后注入到bean中,Spring提供了org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer类,可以方便我们使用注解直接注入properties文件中的配置。 下面我们看下具体如何操作: 首先要新建maven项目,并在pom文件中添加spring依

不列颠 5200

不用买显示器!用USBMMID虚拟显示器软件在Win10上扩展4个屏幕(保姆级教程)

本文提供了一份详细的保姆级教程,指导用户如何在Windows 10系统上,无需购买额外硬件,通过USBMMID虚拟显示器软件扩展出多达4个虚拟屏幕。文章深入解析了虚拟显示器的核心原理,并基于微软IDD框架,手把手教学从软件获取、环境检查到安装配置的全过程,帮助开发者和多任务用户构建高效、免费的虚拟多屏工作站,实现生产力的飞跃。

backprop5master的博客 659

spring管理配置文件的工厂类--PropertiesFactoryBean

spring管理配置文件的工厂类–PropertiesFactoryBean 使用这个工厂的配置,可以很方便的获取配置文件中的属性。具体使用如下; 对于属性配置,一般采用的是键值对的形式,如: key=value 属性配置文件一般使用的是XXX.properties,当然有时候为了避免eclipse把properties文件转码,放到服务器上认不出中文,可以采用XXX.conf的形式管理属性配置。...

wumingdu1234的博客 725

【JAVA】海康威视门禁机ISAPI接口开发,人脸上传更新接口

本文实现了一个HTTP工具类HTTPClientUtil,提供GET/POST/PUT/DELETE请求方法,支持摘要认证。工具类封装了Apache HttpClient,设置连接超时、最大连接数等参数,通过DeviceInfoDTO传递设备IP、端口和认证信息。文中还展示了两个应用示例:userInfoAdd()用于添加人员信息,FaceDataRecordAdd()用于添加人脸数据,均通过POST请求与设备ISAPI接口交互。该工具类简化了HTTP请求处理,支持设备管理系统的集成开发。

qq_27246521的博客 587

深度揭秘!用 DeepSeek 打造超智能电商客服系统全流程

摘要:本文围绕使用 DeepSeek 开发电商智能客服展开详细教程。先介绍前期准备,包括了解 DeepSeek、获取 API 权限与搭建开发环境。接着阐述数据收集预处理,结合电商业务逻辑实现商品与订单信息查询。还提及优化性能的方法,如模型微调、多轮对话管理和错误处理。然后说明了基于 Web 和云平台的部署方案。最后强调持续监控和改进的重要性,通过设置监控指标、收集分析用户反馈来优化系统,助力开发者打造高效电商智能客服。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 7813

spring之@PropertySource注解

PropertySource注解用于指定资源文件读取的位置,它不仅能读取properties文件,也能读取xml文件,并且通过YAML解析器,配合自定义PropertySourceFactory实现解析YAML文件。YAML。

花&败 5372

利用AWVS进行反制

awvs 10.5下载 http://www.32r.com/soft/12986.html

渗透之路,攻防之间皆学问 6653

PropertiesFactoryBean的注入使用

优质文章

lihuihui01的博客 526

STM32F103/F407/H743不同GPIO速度配置(HAL库)对应的最高速度

详细介绍了STM32F103/F407/H743不同GPIO速度配置(HAL库)对应的最高速度。

kevin1499的博客 5588

AutoSAR系列讲解(入门篇)2.4-Runnables可运行实体

讲解一下Runnable和其工程的实际映射

雪云飞星的博客 3万+

Spring依赖注入:自动注入properties文件中的配置

Spring依赖注入:自动注入properties文件中的配置:很多情况下我们需要在配置文件中配置一些属性,然后注入到bean中,Spring提供了org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer类,可以方便我们使用注解直接注入properties文件中的配置。 下面我们看下具体如何操作: 首先要...

qb170217的博客 910

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

以@Value方式注入 properties 配置文件

类中读取XML文件不是太方便,所以使用*.properties是比较好的办法 注入方式获取是最直接,最快捷的。这个操作主要涉三个部分,下面分别介绍: 首先,配置文件准备。这里文件名命名为application.properties: #Updated at Tue Aug 13 14:45:50 CST 2014 #Tue Aug 13 14:45:50 CST 2014 ...

dieshou3715的博客 244

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

spring配置中,properties文件以及xml文件配置问题

一、在springMVC配置读取properties文件

雪夕阳 8907

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

spring配置中加载properties文件方法

首先,遇到一个问题,spring配置中加载properties文件配置如下: &lt;context:property-placeholder ignore-unresolvable="true" location="classpath:config/appconfig.properties"/&gt; 结果运行时发现没加载到properties文件,需要把该配置改为如下: &lt;co...

改变自己 2212

Spring中使用@Value读取porperties文件中的属性值方法总结及注意事项

本文为博主原创,转载请注明出处。   此前曾总结过使用工具类读取properties文件中的属性值,有兴趣的可以看一下。 如何快速获取properties中的配置属性值:https://www.cnblogs.com/zjdxr-up/p/7763485.html java中Properties类及读取properties中属性值:https://www.cnblogs.com/zjd...

weixin_30786657的博客 350

Spring通过@Value注解注入属性的几种方式

场景 假如有以下属性文件dev.properties, 需要注入下面的tag tag=123 通过PropertyPlaceholderConfigurer 代码 @Value("${tag}") private String tag; 通过PreferencesPlaceholderConfigurer 代码: @Value(

caomiao2006的专栏 7075

用 @Value("${xxxx}")注解从配置文件读取值的用法

1. 用法: 从配置properties文件中读取init.password 的值。 [java]view plaincopy @Value("${init.password}") privateStringinitPwd; 2. 在spring的配置文件中加载配置文件dbconfig.properties : [html]view plaincopy...

那些年的代码 1225

Spring配置相关

1.Spring中通过@Value注解注入属性的方式 <!-- 方式一、PropertyPlaceholderConfigurer,访问方式@Value("${tag}") --> <bean id="appProperty" class="org.springframework.beans.factory.config.PropertyPlaceholderCo...

weixin_30248399的博客 76

spring读取配置文件的几种方式

场景 假如有以下属性文件dev.properties, 需要注入下面的tag tag=123 通过PropertyPlaceholderConfigurer <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="loc...

weixin_30663471的博客 80
上一篇: 分库分表数据库中间件对比
下一篇: redis五大类型用法
琅琊山二当家
博客等级 码龄18年 447粉丝 322原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值