Spring01-IoC入门
Spring 框架:
- 表现层(Web层):Spring MVC
- 业务逻辑层(Service层):Spring的IoC
- 数据访问层(DAO层):Spring的jdbcTemplate
Spring中的IoC操作:
将对象的创建交由Spring框架进行管理。
IoC操作分为:IoC配置文件方式和IoC的注解方式。
简单步骤:
1. 第一步:需要导入spring-beans
、spring-core
、spring-context
、spring-expression
这4个jar包),以及 支持日志输出的 commons-logging 和 log4j 的jar包;
2. 第二步:创建一个对象User
package com.lixin.Enity;
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3. 第三步:创建Spring的配置文件,进行Bean的配置
Spring的核心配置文件名称和位置不是固定的。但官方件建议将该核心配置文件放在src目录下,且命名为 applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.lixin.Enity.User"></bean>
</beans>
4. 第四步:测试类-test
package com.lixin.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lixin.Enity.User;
public class test {
public static void main(String[] args) {
//1.创建容器对象,相对于src下的路径
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.向容器“要”user对象
User u=(User) ac.getBean("user");
//3.打印user对象
System.out.println(u);
}
}
运行结果: