易学笔记-第2章:spring中的Bean/2.6 环境参数和占位符

第2章:spring中的Bean/2.6 环境参数和占位符/2.6.1 环境参数/2.6.1.1 概念

  • 概念与设置
  1. 指的是为了区分不同的环境而设置的参数,比如开发环境和生产环境

     


第2章:spring中的Bean/2.6 环境参数和占位符/2.6.1 环境参数/2.6.1.2 参数设置

  • 参数设置
  1. JAVA设置环境变量,比如:System.setProperty("参数名","参数值");比如:

    System.setProperty("targetPlatform","dev");

  2. 从JVM参数中解析,比如:-DParamName = value值
  3. 注解方式 import org.springframework.context.annotation.Profile;

    @Profile("dev")

         public Foo devFoo(@Value("${name}") String name) {

               Foo foo = new Foo();

               foo.setName("dev " + name);

               return foo;

         }


第2章:spring中的Bean/2.6 环境参数和占位符/2.6.1 环境参数/2.6.1.3 参数激活

  • 参数激活
  1. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

               applicationContext.register(Ch2Configuration.class);

               ConfigurableEnvironment environment = applicationContext.getEnvironment();

               //激活某个环境参数

               environment.setActiveProfiles("dev");


第2章:spring中的Bean/2.6 环境参数和占位符/2.6.2 占位符2.6.2.1 概念以及格式

  • 概念以及格式
  1. 类似于参数的形式,而这个参数具体的值在另外的地方设置
  2. 格式:
    1. 使用注解:

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

    2. 声明占位符:
      1. JAVA中:@Value("${占位符名称}"),比如:

        @Value("${name}")

      2. XML文件中:${占位符名称}

第2章:spring中的Bean/2.6 环境参数和占位符/2.6.2 占位符2.6.2.2 占位符赋值

  • 占位符赋值
  1. 声明一个Bean启动占位符解析

    //启动占位符工作机制

         @Bean

         public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {

               return new PropertySourcesPlaceholderConfigurer();

         }

  2. 为占位符赋值

    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

               applicationContext.register(Ch2Configuration.class);

               //获取环境对象

               ConfigurableEnvironment environment = applicationContext.getEnvironment();

               //激活某个环境参数

               environment.setActiveProfiles("dev");

               //给占位符赋值

               MutablePropertySources propertySources = environment.getPropertySources();

               //name为占位符名称,"my foo"为占位符的值

               propertySources.addLast(new MapPropertySource("mapSource", Collections.singletonMap("name", (Object)"my foo")));


第2章:spring中的Bean/2.6 环境参数和占位符/2.6.3 实例(已经编译通过)

  • 实例(已经编译通过)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易学笔记(qq:1776565180)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值