@Profile的作用: Spring容器根据标识激活对应的profile注解,其关联的bean才会被注册到容器中。最常见的用途是区分开发环境,测试环境,生产环境信息
//配置文件DataSource.properties dev.url="localhost" dev.name="admin" dev.pwd="123456" test.url="151.125.33.62" test.name="admin" test.pwd="admin" //对应开发环境信息 public class DevBean { @Value("${dev.url}") private String url; @Value("${dev.name}") private String name; @Value("${dev.pwd}") private String pwd; @Override public String toString() { return "DevBean{" + "url='" + url + '\'' + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } } //对应测试环境信息 public class TestBean { @Value("${test.url}") private String url; @Value("${test.name}") private String name; @Value("${test.pwd}") private String pwd; @Override public String toString() { return "TestBean{" + "url='" + url + '\'' + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } } @Configuration @PropertySource("classpath:com/edu/profile/DataSource.properties") public class Config { @Bean("devBean") @Profile("dev") public DevBean getDevBean(){ return new DevBean(); } @Bean("testBean") @Profile("test") public TestBean getTestBean(){ return new TestBean(); } } public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.getEnvironment().setActiveProfiles("test"); //指定激活目标 annotationConfigApplicationContext.register(Config.class); annotationConfigApplicationContext.refresh(); if(annotationConfigApplicationContext.containsBean("testBean")){ System.out.println("contains testBean"); TestBean testBean = annotationConfigApplicationContext.getBean(TestBean.class); System.out.println(testBean); } if(annotationConfigApplicationContext.containsBean("devBean")){ System.out.println("contains devBean"); DevBean devBean = annotationConfigApplicationContext.getBean(DevBean.class); System.out.println(devBean); } annotationConfigApplicationContext.close(); } }