一个spring+springmvc+mybatis的项目,这里的bean都是通过注解生成的,不是在配置文件里用<bean/>标签配置的,做单元测试时,怎么取得controller层的bean?网上搜了几篇文章,照着试过了,都没解决。
------解决方案--------------------
使用Autowired注解
@Service
public class UserServiceImpl implements UserService {
//...
}
public class UserServiceTest extends BasicTestCase {
@Autowired
private UserService userService;
@Test
public void test() {
//...
}
}
------解决方案--------------------
项目里用 的。
调用
videoInfoService = SpringContextHolder.getBean("videoInfoService",
IVideoInfoService.class);
相关类
package com.ustv.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static <T>T getBean(String beanName , Class<T>clazz) {
return applicationContext.getBean(beanName , clazz);
}
}