fionyang

  为什么说是实用精简版,没办法,工作太忙压力大啊,菜是原罪啊,所以接下来写的一些博客可能都是更偏实用性,精简点,方便自己回顾,快速上手使用即可,毕竟感觉不详细还有书不是吗。

  profile是用来干什么的?简单来说,就是现实需求中,不同环境下我们所要的某个bean可能会有所不同。

  1. 配置profile bean

    可以使用@Profile注解指定某个bean属于哪个profile。比如下雨天时我需要的工具是雨伞,所以可以如下配置:

@Configuration
@Profile("rainyday")
public class RainyDayConfig {
      @Bean
      public Tool tool() {
            return new Umbrella();   //假设Umbrella继承了Tool
      }
}

  这里@Profile注解用在了类级别上,表明只有rainyday profile激活时,这个配置类中的bean才会被创建,相反,当rainyday profile没有被激活时,带有@Bean注解的方法会被忽略。同理,现在晴天时,我可能需要阳伞,可如下配置:

@Configuration
@Profile("sunnyday")
public class SunnyDayConfig {
      @Bean
      public Tool tool() {
            return new Sunshade();   //假设Sunshade继承了Tool
      }
}

    与下雨天(rainyday)一样,上面这段配置类中使用@Bean注解的方法也只有在sunnyday profile激活时,才可以生效。

  不过这个还是有点麻烦,需要两个配置类,这是Spring 3.1中的唯一写法,但是Spring 3.2之后,就可以这样写了,如下:

@Configuration
public class ToolConfig {
      @Bean
      @Profile("rainyday")
      public Tool umbrellaTool() {
            return new Umbrella();   //假设Umbrella继承了Tool
      }
      
      @Bean
      @Profile("sunnyday")
      public Tool sunshadeTool() {
            return new Sunshade();   //假设Sunshade继承了Tool
      }

      @Bean
      public Shoes shoes() {
            return new Shoes(); 
      }
}

  这样是不是就方便多了,我只需要一个配置类,需要注意的是,umbrellaTool方法只会在下雨天(rainyday)profile激活时生效并创建bean,sunshadeTool方法只会在晴天(sunnyday)profile激活时生效并创建bean,而shoes方法没有指定profile,它会始终生效并创建bean。

  上面这些都是使用JavaConfig类方式在声明profile,其实也可在XML中配置profile bean,只需在<beans>标签中添加profile属性即可,这里不详细介绍了,可参考书。

2. 激活profile

  profile是配置好了,但是怎么激活profile呢?别急,下面讲的就是这些啦

相关文章: