Spring In Action-3.2@Conditional条件化Bean

Posted 第二天半

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring In Action-3.2@Conditional条件化Bean相关的知识,希望对你有一定的参考价值。

@Conditional
根据某个条件来决定是否创建Bean实例

代码下载地址:http://download.csdn.net/download/poiuy1991719/9965794

 

 

创建一个Bean类:

package com.bean.conditional;

import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

@Component("magicBeanName")//重命名:配置类里面的方法与之对应
@Conditional(MagicCheck.class)//决定是否创建Bean的条件类
public class MagicBean {
    private String name="MagicBean";
    public MagicBean() {
        System.out.println("MagicBean:实例化");
    }
    
    public void showName(){
        System.out.println("Show Name is:"+name);
    }
}

 

创建一个Config配置类:配置类指定了一个Check类:

package com.bean.conditional;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages={"com.bean"})
public class BeanConfigs {

    @Bean
    @Conditional(MagicCheck.class)//决定是否创建Bean对象
    public MagicBean magicBeanName(){//方法名来源,Bean类的注解:@Component("magicBeanName")
        return new MagicBean();
    }
}

 

Check类决定是否创建Bean的实例:Check类需是Condition类的一个实现:

package com.bean.conditional;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

//决定Bean的创建,需是Condition的一个接口
public class MagicCheck implements Condition {

    public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) {
        return true;//创建Bean实例
//        return false;//不创建Bean实例
    }
}

 

测试类:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.bean.conditional.BeanConfigs;
import com.bean.conditional.MagicBean;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={BeanConfigs.class})
public class test {
	@Autowired
	MagicBean mb;
	
	@Test
	public void selfTest(){
		if(mb==null){
			System.out.println("MagicCheck类决定了Bean的创建,MagicCheck类方法返回:false");
		}else{
			System.out.println("MagicCheck类决定了Bean的创建,MagicCheck类方法返回:true");
			mb.showName();
		}
	}
}

  


以上是关于Spring In Action-3.2@Conditional条件化Bean的主要内容,如果未能解决你的问题,请参考以下文章

Spring 数据存储库:findBySomething***In*** 和结果顺序

springJdbc in 查询,Spring namedParameterJdbcTemplate in查询

html in spring

Spring aop学习整理(spring in action):spring AOP

spring in action 4 线路图

Spring in Action Core Spring:Wiring Beans