两种获取Bean方式
方式1
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Test
public void testApplicationContext() {
AlphaDao alphaDao = applicationContext.getBean(AlphaDao.class);
System.out.println(alphaDao.select());
}
方式2
// 使用Bean,没有必要去通过容器获取,只需要声明给当前容器注入
@Autowired
private AlphaDao alphaDao;
@Test
public void testDI() {
System.out.println(alphaDao.select());
}
完整测试类代码
@SpringBootTest
//保证测试类和正式项目所用配置类保持一致
@ContextConfiguration(classes = CampusCommunityApplication.class)
//哪个类需要spring容器,哪个类就实现接口得到spring容器
class CampusCommunityApplicationTests implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Test
public void testApplicationContext() {
AlphaDao alphaDao = applicationContext.getBean(AlphaDao.class);
System.out.println(alphaDao.select());
}
// 使用Bean,没有必要去通过容器获取,只需要声明给当前容器注入
@Autowired
private AlphaDao alphaDao;
@Test
public void testDI() {
System.out.println(alphaDao.select());
}
}