@Profile注解的使用——阅读开源项目中的代码
作用:指定Bean加载的生产环境
例子1:
//建立Bean实体 public class DemoBean { private String content; public DemoBean(String content) { super(); this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } ===================================== //使用@Configuration,区分不同的生产环境 import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * Created by sang on 16-12-13. */ @Configuration public class ProfileConfig { @Bean @Profile("dev") public DemoBean devDemoBean() { return new DemoBean("dev"); } @Bean @Profile("prod") public DemoBean prodDemoBean() { return new DemoBean("prod"); } } ========================== //设置生产环境,注册主配置类 import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Created by sang on 16-12-13. */ public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod");
context.register(ProfileConfig.class); context.refresh(); DemoBean bean = context.getBean(DemoBean.class); System.out.println(bean.getContent()); context.close(); } }
使用方法:

浙公网安备 33010602011771号