第一种方法:@Test方法
1.@Autowired
功能:
a.为我们注入一个定义好的bean
b.主要还是能解决重复生成实例的问题
c. 将 Spring 容器中的 bean 自动的和我们需要的这个 bean 的类组装在一起
最常被使用的ApplicationContext接口实现:
FileSystemXmIApplicationContext:
该容器从XML文件中加载已被定义的 bean。
在这里,你需要提供给构造器XML文件的完整路径。
ClassPathXmIApplicationContext:
该容器从XML文件中加载已被定义的bean。
在这里,你不需要提供XML文件的完整路径,
只需正确配置CLASSPATH 环境变量即可,
因为,容器会从CLASSPATH中搜索bean配置文件。
WebXmIApplicationContext:
该容器会在一个web应用程序的范围内加载在XML文件中已被定义的 bean。
.getBean方法:
通过ApplicationContext的getBean方法来获取Spring容器中已初始化的bean
public class TestUtil {1.//新建测试类
@Autowired
UserPrintDao userPrintDao;2.//注入需要的dao层
@Test
public void test1(){3.//单元测试
4.//获取容器对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
5.//获取接口
UserPrintDao userPrintDao = context.getBean(UserPrintDao.class);
6.//使用接口方法
userPrintDao.addList(list);
}```
第二种方法:mian方法
public class TestUtil {1.//新建测试类
public static void main(String[] args){2.//mian方法测试
3.//获取容器对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");//classpath可省略
4.//获取接口
UserPrintDao userPrintDao = context.getBean("userPrintDao",UserPrintDao.class);//userPrintDao可省略
5.//使用接口方法
userPrintDao.addList(list);
}