步骤:
1
创建一个web project工程(day1)
在src目录中创建一个com.it.csx_ioc包
2 导入jar包
Spring核心jar包 springjar包的依赖。
3
在com.it.csx_ioc包中 创建接口和实现类
UserService接口
// 接口
public interface UserService {
// 方法
public void adduser();
}
UserServiceImpl类
//创建UserServiceImpl类
public class UserServiceImpl implements UserService {
String name;
@Override
public void adduser() {
// TODO Auto-generated method stub
System.out.println("arrUser....");
}
// 空参构造方法
public UserServiceImpl() {
super();
// TODO Auto-generated constructor stub
}
// 有参构造方法
public UserServiceImpl(String name) {
super();
this.name = name;
}
}
4 在 com.it.csx_ioc包中创建一个XML文件。
名字是beans.xml
添加xml文件的约束 (IOC beans.txt文件中)或者从
spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html复制过来
5 编写beans.xml文件
<!-- <bean>标签 表示spring创建一个UserServiceImpl类的对象 ,相当于 UserServiceImpl a= new UserServiceImpl()
id属性: 用于Spring获取UserServiceImpl类的实例对象
class属性: 你要创建哪个类的实例,那么这里就写哪个类的全路径(com.it.csx_ioc.UserServiceImpl)
-->
<bean id="userServiceId" class="com.it.csx_ioc.UserServiceImpl"> </bean>
6
在com.it.csx_ioc包中创建test.java文件
编写测试程序 test.java
程序如下:
// 测试程序(测试spring的IOC)
public class test {
public static void main(String[] args) {
//1 获取容器
String xmlPath="com/it/csx_ioc/beans.xml";
ApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlPath);
// 2 获取UserServiceImpl类的实例 。相当于new一个对象
UserServiceImpl userservice=(UserServiceImpl) applicationContext.getBean("userServiceId");
// 创建一个对象
// UserServiceImpl userservice= new UserServiceImpl();
// 调用UserServiceImpl类中的addUser方法
userservice.adduser();
}
}
7 运行程序