易学笔记-第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 实例(已经编译通过)

猜你喜欢

转载自blog.csdn.net/u011830122/article/details/83904801
今日推荐