之前开发,new 一个对象 spring之后,由spring创建对象实例–>ioc(inverse of control)控制反转
public interface UserService { public void addUser(); } public class UserServiceImpl implements UserService { public void addUser() { System.out.println("add user"); } } public class TestIoc { @Test public void demo1(){ //之前 UserService userService = new UserServiceImpl(); userService.addUser(); } @Test public void demo2(){ //使用spring //获取容器 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Beans.xml"); //从spring中获取对象 UserService userService = (UserService) applicationContext.getBean("userService"); userService.addUser(); } }配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--bean 配置需要创建的对象 ,id:用于之后从spring容器中获取实例,class:需要创建实例的全限定类名--> <bean id="userService" class="ioc.UserServiceImpl"></bean> </beans>