博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring注解 之属性赋值@Value和@PropertySource
阅读量:2456 次
发布时间:2019-05-10

本文共 1813 字,大约阅读时间需要 6 分钟。

配置文件person.properties

person.nickName=张飞

实体Person

import lombok.Data;import org.springframework.beans.factory.annotation.Value;@Datapublic class Person {
//使用@Value赋值; //1、基本数值 //2、可以写SpEL; #{} //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值) @Value("刘备") private String name; @Value("#{50-20}") private Integer age; @Value("${person.nickName}") private String nickName;}

Spring配置文件Config.java

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值@PropertySource(value={
"classpath:/person.properties"})@Configurationpublic class Config {
@Bean public Person person(){
return new Person(); }}

单元测试

import org.junit.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.core.env.ConfigurableEnvironment;public class IOCTest {
@Test public void test01(){
//1、创建ioc容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); printBeans(applicationContext); System.out.println("============="); Person person = (Person) applicationContext.getBean("person"); System.out.println(person); ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.nickName"); System.out.println(property); //关闭容器 applicationContext.close(); } private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] definitionNames = applicationContext.getBeanDefinitionNames(); for (String name : definitionNames) {
System.out.println(name); } }}

转载地址:http://dgdhb.baihongyu.com/

你可能感兴趣的文章
shell 点文件_Shell点文件可以为您做什么
查看>>
zsh 简单高效使用技巧_使用zsh提高生产力的5个技巧
查看>>
perl子例程_子例程签名在Perl 6中如何工作
查看>>
开源 js图形_年度计算机图形会议鼓励使用开源
查看>>
多步骤建立镜像_通过四个步骤建立更多可信赖的团队
查看>>
linux中top命令_在Linux中使用top命令的提示
查看>>
管理工具 tools不可用_赶紧为管理员准备的10种杀手tools工具
查看>>
sysadmin默认密码_sysadmin的SELinux指南:42个主要问题的答案
查看>>
sysadmin默认密码_sysadmin的Ansible指南:如何简化任务
查看>>
linux开源游戏_适用于Linux的5个开源策略和模拟游戏
查看>>
Buffer看到透明的员工薪资政策有明显好处
查看>>
raspberry pi_将您的旧Raspberry Pi变成自动备份服务器
查看>>
幕后产品_3月17日#OpenOrgChat:幕后开放组织
查看>>
前5名:Linux计算机故事,超酷的docker工具,2016年有10个项目值得分派
查看>>
sphinx 文档_像埃及人一样的Doc:使用Sphinx管理项目文档
查看>>
git运行 vagrant_前5名:Vagrant,Git,GitHub等
查看>>
docker strace_前5名:适用于初学者,strace,Kubernetes,Docker,专利和DevOps的OpenStack
查看>>
linux发行版 哪个快_前5名:您使用哪个Linux发行版?,用于音乐的Linux等
查看>>
开源社区_开源社区需要导师
查看>>
openstack 云_面向初学者的OpenStack云简介
查看>>