spring获取配置文件中的值

如何在spring中读取配置文件的值呢?方式有很多种,这里介绍一种。

干脆直接贴代码:
一、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>com.alex</groupId>
    <artifactId>spring-config</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>helloIdea</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

二、pojo类

package com.alex.pojo;

import lombok.Data;

/**
 * @author alex
 * @Title: User
 * @Description: TODO
 * @date 2019/2/12 17:28
 */
@Data
public class User {
    private String name;
    private String sex;
}

三、目录结构及配置文件properties
目录结构

user1.properties内容:
	user1.name=user1Name
	user1.sex=user1Sex
user2.properties内容:
	user2.name=user2Name
	user2.sex=user2Sex

四、配置文件类PropertyConfig

package com.alex.property;

import com.alex.pojo.User;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

/**
 * @author alex
 * @Title: PropertyConfig
 * @Description: TODO
 * @date 2019/2/12 17:28
 */
@Data
@Configuration
@PropertySources({@PropertySource(value="classpath:com/alex/properties/user1.properties"),
        @PropertySource(value= "classpath:user2.properties")})
public class PropertyConfig {
    @Value("${user1.name}")
    private String name;
    @Value("${user1.sex}")
    private String sex;
    @Autowired
    private Environment env;
    @Bean(name="user2")
    public User getUser(){
        User user = new User();
        user.setName(this.env.getProperty("user2.name"));
        user.setSex(this.env.getProperty("user2.sex"));
        return user;
    }
    @Bean(name="user1")
    public User findUser(){
        User user = new User();
        user.setName(this.getName());
        user.setSex(this.getSex());
        return user;
    }

    /**
     * 这段代码是必要的
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

五、测试主方法

package com.alex;

import com.alex.pojo.User;
import com.alex.property.PropertyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author alex
 * @Title: Mymain
 * @Description: TODO
 * @date 2019/2/12 17:34
 */
public class Mymain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PropertyConfig.class);
        System.out.println("-------------从环境对象中获取变量的值---------------");
        System.out.println(context.getEnvironment().getProperty("user1.name"));
        System.out.println(context.getEnvironment().getProperty("user2.name"));
        System.out.println("-------------将环境对象中的值存储到user2对象-----------------");
        User user2 = (User) context.getBean("user2");
        System.out.println(user2.getName());
        System.out.println(user2.getSex());
        System.out.println("--------------使用@value获取值并存储到user1对象--------");
        User user1 = (User)context.getBean("user1");
        System.out.println(user1.getName());
        System.out.println(user1.getSex());
    }
}

六、结果

-------------从环境对象中获取变量的值---------------
user1Name
user2Name
-------------将环境对象中的值存储到user2对象-----------------
user2Name
user2Sex
--------------使用@value获取值并存储到user1对象--------
user1Name
user1Sex

七、有收获记得点赞哟。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值