实现 BeanFactoηAware 接口的 bean 可以直接访问 Spring 容器,被容器创建以后,它会拥有一个指向 Spring 容器的引用,可以利用该bean根据传入参数动态获取被spring工厂加载的bean,实现方法如下:

      第一步,需在spring的配置文件applicationContext.xml中启用自动注解扫描功能。

       

<!-- 启用注解扫描 -->
	<context:annotation-config/>
     第二步,开发 BeanFactoηAware接口的实现类BfBasic

   

package com.hundsun.demo.service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Service;

/**
 * 利用BeanFactoryAware接口通过bean的名称获取bean对象
 *<p></p>
 * @author: darren
 * @history:
 ************************************************
 * @file: BfBasic.java
 * All right reserved.
 ***********************************************
 */
@Service("beanFac")
public class BfBasic implements BeanFactoryAware {
	
	private BeanFactory beanFactory;

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory=beanFactory;
	}
	
	public void executeProcess(String beanName){
		BasicService  bs=(BasicService) beanFactory.getBean(beanName);
		bs.say();
	}

}

    第三步,开发接口及serviceBean多实现

  

package com.hundsun.demo.service;

public interface BasicService {
   public void say();
}

    两个实现服务bean

package com.hundsun.demo.service.impl;

import org.springframework.stereotype.Service;

import com.hundsun.demo.service.BasicService;


@Service("serviceA")
public class ABasicServiceImpl implements BasicService {

	@Override
	public void say() {
		System.out.println("current serviceBean is:"+ABasicServiceImpl.class);

	}

}

package com.hundsun.demo.service.impl;

import org.springframework.stereotype.Service;

import com.hundsun.demo.service.BasicService;


@Service("serviceB")
public class BBasicServiceImpl implements BasicService {

	@Override
	public void say() {
		System.out.println("current serviceBean is:"+this.toString());
	}

	public static void main(String[] args) {
		new BBasicServiceImpl().say();
	}
	
}

   第四步,在业务逻辑中调用

package com.hundsun.demo.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hundsun.demo.dao.SysCodeDao;
import com.hundsun.demo.service.BfBasic;
import com.hundsun.demo.service.SysCodeService;



@Service("sysCodeService")
public class SysCodeServiceImpl implements SysCodeService {
	
	@Autowired
	private SysCodeDao sysCodeDao;
	
	@Autowired
	private BfBasic bfBasic;

	@Override
	public String buildCode(int type, String preStr) {
		return sysCodeDao.buildCode(type, preStr);
	}

	@Override
	public Date getSysDate() {
		bfBasic.executeProcess("serviceA");
		return sysCodeDao.getSysDate();
	}

}

  代码标红区域为服务调用。

 以上为一个简单的应用实例,通过此可以实现不同业务细类的调度器方案。


  

    

      


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐