Spring属性赋值

Spring 属性赋值

Spring中通过 @Value 给Bean赋值

@Value赋值方式有:

  1. 基本数值
  2. 可以写SpEL表达式:#{}
  3. 可以写${};取出配置文件中的值(在运行环境变量里面的值)

例如:

package com.xiaochao.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;

/**
 * @program: springDemoCode
 * @description:
 * @author: 小超
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

    //基本数值(包括字符串,数字)
    @Value("张三")
    private String name;

    //SpEl表达式:#{}
    @Value("#{20-2}")
    private int age;

    //${}:取出配置文件中的值(在运行环境变量里面的值)
    @Value("${person.nickName}")
    private String nickName;

}

配置文件person.properties 放置在resource目录下

person.nickName=Tom

配置文件MainConfigOfPropertyValues

package com.xiaochao.config;

import com.xiaochao.pojo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @program: springDemoCode
 * @description:
 * @author: 小超
 **/
//使用@PropertySource读取外部配置文件person.properties中的K/V保存到运行的环境变量中
@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {

    @Bean
    public Person person(){
        return new Person();
    }

}

测试:

package com.xiaochao.test;

import com.xiaochao.config.MainConfigOfPropertyValues;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * @program: springDemoCode
 * @description:
 * @author: 小超
 **/
public class IOCTest_PropertyValue {

    AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);

    @Test
    public void test01(){
        System.out.println(applicationContext.getBean("person"));

        //获取properties文件中的环境
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);
        applicationContext.close();
    }
}

测试结果:

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值