`

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

 
阅读更多

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

 

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

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

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

<projectxmlns="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.PropertiesFactoryBeanorg.springframework.beans.factory.config.PreferencesPlaceholderConfigurer的实例配置:

如下spring配置文件appContext.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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-scanbase-package="cn.outofmemory.hellospring.properties.annotation"></context:component-scan><beanid="configProperties"class="org.springframework.beans.factory.config.PropertiesFactoryBean"><propertyname="locations"><list><value>classpath*:application.properties</value></list></property></bean><beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"><propertyname="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;@ComponentpublicclassMySQLConnectionInfo{@Value("#{configProperties['mysql.url']}")privateString url;@Value("#{configProperties['mysql.userName']}")privateString userName;@Value("#{configProperties['mysql.password']}")privateString password;/**
     * @return the url
     */publicString getUrl(){return url;}/**
     * @return the userName
     */publicString getUserName(){return userName;}/**
     * @return the password
     */publicString 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!
 *
 */publicclassApp{publicstaticvoid main(String[] args ){ApplicationContext appContext =newClassPathXmlApplicationContext("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的实例,然后打印出来,运行程序会输出配置文件中配置的值。

分享到:
评论

相关推荐

    spring学习:依赖注入的几种方式讨论

    本文将深入探讨Spring中的依赖注入实现方式,以及如何通过样例文件`sample-autoconfig`进行理解和实践。 一、XML配置的依赖注入 在Spring早期版本中,XML配置是最常见的DI方式。开发者在Spring的配置文件(如`...

    Spring依赖包和配置文件

    2. **自动配置**:Spring Boot引入了自动配置的概念,根据类路径中的jar文件自动配置Spring应用,减少了大量手动配置工作。 3. **注解驱动**:Spring 3.0以后,注解成为主流,如@Service、@Repository、@Controller...

    spring依赖注入例子

    在Spring中,依赖注入可以通过XML配置、注解或Java配置实现。本例子主要关注基于注解的依赖注入,这是一个现代且更简洁的方法。 首先,让我们理解一下依赖注入的基本概念。在面向对象编程中,一个类可能会依赖于...

    SpringBoot第 5 讲:SpringBoot+properties配置文件读取

    在需要配置信息的类中,可以通过依赖注入获取: ```java @Autowired private Environment env; ``` 然后你可以通过`env.getProperty("key")`来获取配置项。 4. **@ConfigurationProperties** 对于复杂的配置...

    spring,配置文件从属性文件读取JDBC连接的相关参数

    在Spring框架中,配置文件是核心组件之一,用于定义bean的生命周期、依赖关系以及各种应用配置。当涉及到数据库操作时,通常需要从属性文件中读取JDBC连接的相关参数,如数据库URL、用户名、密码等。这样的做法可以...

    spring-demo09-读取properties配置文件内容.zip

    在Spring框架中,读取`properties`配置文件是常见的任务,用于管理应用程序的配置信息,如数据库连接字符串、服务端口、系统环境变量等。本文将深入探讨如何在Spring项目中实现这一功能。 首先,我们需要一个`...

    day38 17-Spring的Bean的属性注入:注解方式

    在Spring框架中,Bean的属性注入是核心功能之一,它允许开发者在不编写代码的情况下配置对象的依赖关系。本文将详细讲解使用注解方式进行Bean属性注入的方法,以及相关的源码和工具应用。 首先,让我们了解Spring中...

    SpringBoot框架Datasource注入

    在Spring Boot中,我们通常通过自动配置和依赖注入来轻松地管理`DataSource`。 首先,我们需要理解`bean`这个概念。在Spring框架中,`bean`是一个由Spring IoC(Inversion of Control,控制反转)容器管理的对象。...

    在非spring注解类中使用spring容器中的bean_普通类中使用yml配置文件中的配置信息

    然而,在某些情况下,我们可能需要在非Spring注解的类中访问Spring容器中的Bean,或者在这些类中使用YAML配置文件中的配置信息。本篇将详细介绍如何在这样的场景下实现这一目标。 首先,让我们来理解如何在非Spring...

    项目配置文件( spring-mvc.xml spring-mybatis.xml web.xml log4j.properties)

    这里提到的四个关键配置文件——`spring-mvc.xml`、`spring-mybatis.xml`、`web.xml`以及`log4j.properties`,对于一个基于Java的Web应用来说至关重要,特别是使用Spring MVC和MyBatis框架的时候。接下来,我们将...

    SpringBoot获取yml和properties配置文件的内容

    首先,我们需要在`pom.xml`文件中添加`spring-boot-configuration-processor`依赖,这样Spring Boot就可以处理配置属性并生成元数据: ```xml &lt;groupId&gt;org.springframework.boot &lt;artifactId&gt;spring-boot-...

    spring 配置文件 归类

    总的来说,Spring的配置文件是实现IOC和AOP的关键,通过合理的配置,可以实现对象的管理、依赖注入以及面向切面的编程,从而简化代码,提高可维护性。在编写配置文件时,理解每个元素的作用以及如何组合使用它们是至...

    Spring配置文件集合

    9. `applicationContext.xml`: 这是Spring容器的主配置文件,用于定义Bean的实例化、依赖注入、bean之间的关系等。它是Spring应用上下文的基础,包含了所有业务对象和服务的配置。 通过这些配置文件的组合,我们...

    day38 14-Spring的Bean的属性的注入:集合属性的注入

    在Spring框架中,Bean的属性注入是核心功能之一,它允许我们通过配置文件或注解来设置Bean的属性值,从而实现对象的依赖管理。在本主题“day38 14-Spring的Bean的属性的注入:集合属性的注入”中,我们将深入探讨...

    spring4.0引用properties

    `PropertyPlaceholderConfigurer`是Spring早期版本中用于注入properties文件中值的bean,而`@ConfigurationProperties`是Spring Boot引入的,更适合现代Spring应用。 使用`PropertyPlaceholderConfigurer`的例子...

    Spring技术内幕:深入解析Spring架构与设计原理

    2. **自动配置**:Spring Boot会根据添加到项目中的jar包来自动配置Spring应用。例如,如果项目中引入了Spring Data JPA,那么Spring Boot会自动配置数据源和实体管理器工厂。 3. **外部配置**:可以通过properties...

    spring依赖包

    在这个"spring依赖包"中,我们很显然会找到与Spring框架相关的各类JAR文件,特别是那些支持日志功能的库。 首先,让我们来详细了解一下Spring框架的核心组成部分: 1. **Spring Core**: 这是Spring框架的基础,...

    谈谈Spring 注入properties文件总结

    Spring框架在处理应用程序的配置和依赖注入方面非常强大,它允许开发者从外部的properties文件中加载配置信息,以便于管理数据库连接、系统属性等。在本文中,我们将深入探讨Spring如何注入properties文件,并总结几...

    day38 13-Spring的Bean的属性的注入:SpEL注入

    同时,它与Spring的其他特性,如AOP(面向切面编程)和Bean的生命周期管理,无缝集成,提供了高度灵活和强大的依赖注入解决方案。 在实际开发中,结合`@ConfigurationProperties`和SpEL,我们可以实现更高级的配置...

    spring 设值注入

    设值注入是Spring依赖注入(Dependency Injection,DI)的一种形式,它有助于降低代码间的耦合度,提高应用程序的可测试性和可维护性。 首先,我们需要理解什么是bean。在Spring中,bean是一个由Spring IoC容器管理...

Global site tag (gtag.js) - Google Analytics