Spring注解--@Profile的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fangxinde/article/details/82808091

@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);
	}
}

 运行结果出错,容器中找不到此实例。

扫描二维码关注公众号,回复: 3303255 查看本文章

猜你喜欢

转载自blog.csdn.net/fangxinde/article/details/82808091