1. 程式人生 > >Spring註解[email protected]的使用

Spring註解[email protected]的使用

@Profile的作用:當容器根據標識啟用對應的@Profile註解時,其所關聯的bean類才會註冊到容器。但容器不能或找不到對應的@Profile,就不生成bean例項。

建立配置類MainConfigOfProfile.java,生成bean方法yellow()被@Profile修飾,此註解被容器啟用後,例項才會註冊到容器。

@Configuration
public class MainConfigOfProfile{
//@Profile關聯Yellow類,當容器啟用此註解時,此bean才會註冊到容器
	@Profile("test") 
	@Bean
	public Yellow yellow(){
		return new Yellow();
	}
	 
}

測試類:

容器以【test1】為標識,查詢對應的@Profile,因標識不符【正確標識為test】,不能啟用@Profile,故bean不能註冊到容器。

執行出現錯誤。

public class IOCTest_Profile {
	@Test
	public void test01(){
		@SuppressWarnings("resource")
                //1.建立容器
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		
		//2.設定需要啟用對應的@Profile
		applicationContext.getEnvironment().setActiveProfiles("test1");
		//3.註冊主配置類
		applicationContext.register(MainConfigOfProfile.class);
		//4.重新整理容器
		applicationContext.refresh();
		Yellow yellow = applicationContext.getBean(Yellow.class);
		System.out.println(yellow);
	}
}

 執行結果出錯,容器中找不到此例項。