1.在@Test中无法使用原因:因为注解是spring容器解析的,要想让注解能够生效的话是需要spring容器启动的,这就是web项目启动环境下使用的。在junit里面测试,要想让Spring容器管理bean完成自动注入的话,可以使用Spring的junit测试工具注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:spring/spring.xml"})
@Transactional
public class RegionServiceTest extends TestCase {
@Resource(name="regionService")
private RegionService regionService;
@Test
public void testFindRegions() {
try {
List<Region> regions = regionService.findRegions();
System.out.println(regions.size());
} catch (Exception e) {
e.printStackTrace();
}
}
2.强转类型的时候,应选择为接口,而不是实现类。ExpressService为接口:
ExpressService service = (ExpressService) SpringUtil.getBean(className);
3.检查配置文件applicationContext.xml是否扫描了注解。
<context:component-scan base-package="***">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>