最新消息: 新版网站上线了!!!

spring Profile如何为不同环境提供不同的配置支持

˵Ã÷

ProfileΪÔÚ²»Í¬»·¾³ÏÂʹÓò»Í¬µÄÅäÖÃÌṩÁËÖ§³Ö£¨¿ª·¢»·¾³ÏµÄÅäÖúÍÉú²ú»·¾³ÏµÄÅäÖÿ϶¨ÊDz»Í¬µÄ£¬ ÀýÈ磬 Êý¾Ý¿âµÄÅäÖã© ¡£ ÔÚspring¿ª·¢ÖÐÓÃ@Profile ×¢½âʹÓÃÀ´Ñ¡ÔñÐÐÅäÖÃϵͳÊôÐÔ¡£¶øÔÚspring boot ÖÐʹÓøú·½±ã¡£

´«Í³µÄspring ProfileʹÓÃ

²Î¿¼¡¶javaEE ·¢¿ªµÄµß¸²Õß¡·Ö÷Òª½áºÏ @Configuration @Bean ×¢½âʹÓà ÈçÏ´úÂë £º

@Configuration //ÉùÃ÷×¢½âÀà
public class ProfileConfig {@Bean@Profile("dev") //1 
  public DemoBean devDemoBean() {
    return new DemoBean("from development profile");
  }@Bean@Profile("prod") //2public DemoBean prodDemoBean() {
  return new DemoBean("from production profile");
}
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.getEnvironment().setActiveProfiles("prod"); //1 »ñÈ¡ÈÝÆ÷×¢Èë»·¾³ÅäÖà £¬prodDemoBean ·½·¨£¬Èç¹ûÉèÖõÄÊÇ¡°Ddev¡± ÔËÐÐDevDemoBean·½·¨ ¡£
        context.register(ProfileConfig.class); //2
        context.refresh(); //3
        DemoBean demoBean = context.getBean(DemoBean.class);
        System.out.println(demoBean.getContent());
        context.close();
    }
}

spring boot ·½·¨ÖÐʹÓãº

¶Ô²»Í¬»·¾³Ìṩ²»Í¬ÅäÖù¦ÄܵÄÖ§³Ö£¬¿ÉÒÔͨ¹ý¼¤»î¡¢Ö¸¶¨²ÎÊýµÈ·½Ê½¿ìËÙÇл»»·¾³

1¡¢¶àprofileÎļþÐÎʽ£ºapplication-{profile}.properties/yml

spring µÄÅäÖÃÎļþÓÐÁ½ÖÖÐÎʽ Ò»ÖÖÊÇproperties Îļþ £¬Ò»ÖÖÊÇ yml Îļþ £¬²»¹ÜÄÄÒ»ÖÖ¶¼¿ÉÒÔÓÃÎļþÃüÃûµÄÐÎʽÇø·Ö²»Í¬»·¾³µÄÅäÖà È磺

¿ª·¢»·¾³ £ºapplication-dev.properties

Éú²ú»·¾³£ºapplication-prod.properties

È»ºóÔÚ application.properties ÎļþÖм¤»î£¬µ±Ç°µÄ»·¾³ £ºspring.frofiles.active = dev ,¼¤»î¿ª·¢»·¾³

2.¶àprofileÎĵµ¿éģʽ£º Õâ¸öÖ»Õë¶ÔymlÎļþ¸ñʽ £¬·½±ãдÔÚÒ»¸öÎļþÖÐ £¬ÈçÏÂͼ

3.¼¤»î·½Ê½£º

  • ¨C ÃüÁîÐÐ --spring.profiles.active=dev
  • ¨C ÅäÖÃÎļþ spring.profiles.active=dev
  • ¨C jvm²ÎÊý ¨CDspring.profiles.active=dev

ÒÔÉϾÍÊDZ¾ÎĵÄÈ«²¿ÄÚÈÝ£¬Ï£Íû¶Ô´ó¼ÒµÄѧϰÓÐËù°ïÖú£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö½Å±¾Ö®¼Ò¡£

转载请注明:谷谷点程序 » spring Profile如何为不同环境提供不同的配置支持