spring基本认识(1)
- spring是用了去掉重复代码
- spring还可以用来去耦合,利用反射机制来创建对象
step1 导入jar包
package cn.itcast.a_hello;
public class User {
private int id;
private String name;
public User() {
super();
System.out.println("------User对象创建------");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void init_user() {
System.out.println("创建对象之后,初始化");
}
public void destroy_user() {
System.out.println("IOC容器销毁,user对象回收!");
}
}
step2 创建IOC容器
package cn.itcast.a_hello;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class App1_get_ioc {
//(方便)直接得到IOC容器对象
@Test
public void testAc() throws Exception {
// 得到IOC容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/a_hello/applicationContext.xml");
// 从容器中获取bean
User user = (User) ac.getBean("user");
System.out.println(user);
}
}
如果以前我们需要
User user=new User();
现在spring可以帮助我们实例化对象
step3 配置XML文件
applicationContext.xml也可以写成bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="user" class="cn.itcast.a_hello.User"></bean>
</beans>