从 Spring 容器取 Service Bean 报错

版权声明:大家好,我是笨笨,笨笨的笨,笨笨的笨,转载请注明出处,谢谢! https://blog.csdn.net/jx520/article/details/88362106

昨天想写个测试,发现取不到 sevice 的 bean。原因是要取接口class而非实现类class

提个基类,方便从容器取 bean

package com.jerryjin.mapper;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import junit.framework.TestCase;

/**
 * 为了取 bean 方便提个基类。
 */
public class BaseTest extends TestCase {
	//初始化上下文;
	protected static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
	//按类型提取 getBean("jerryUserService");
    public <T> T getBean(Class<T> requiredType) {
    	return context.getBean(requiredType);
    }
    //按别名取 getBean(IJerryUserService.calss); 注意按class取Service要用接口
    public Object getBean(String requiredType) {
    	return context.getBean(requiredType);
    }
	
}

正例:

  • 用别名
public class JerryUserServiceTest extends BaseTest {
	public void testBuildUserName() {
		IWeChatUserService weChatUserService = (IWeChatUserService)getBean("weChatUserService");
		System.out.println(weChatUserService.buildUserName());
	}
}
  • 用class
    要用接口的class
public class JerryUserServiceTest extends BaseTest {
	public void testBuildUserName() {
		IWeChatUserService weChatUserService = (IWeChatUserService)getBean(IWeChatUserService.class);
		System.out.println(weChatUserService.buildUserName());
	}
}

反例:

  • 用class
    直接用实现类的class 会报错
public class JerryUserServiceTest extends BaseTest {
	public void testBuildUserName() {
		IWeChatUserService weChatUserService = (IWeChatUserService)getBean(WeChatUserService.class);
		System.out.println(weChatUserService.buildUserName());
	}
}

猜你喜欢

转载自blog.csdn.net/jx520/article/details/88362106