前置条件:导入spring中需要的jar包
Spring的核心就是IOC(控制反转,及在获取对象时需要需new一个对象,使用IOC便是让别人给你一个对象)和AOP(面向切面)。
IOC的基本使用:
1、实体类创建:
package com.msb.bean;
public class Person {
private int id;
private String name;
private int age;
private String gender;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
2、ioc.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标签,表示要创建的bean对象
id:唯一标识符
class:要创建的bean对象的完全地址
-->
<bean id="person" class="com.msb.bean.Person">
<!--
property:属性及赋值
-->
<property name="id" value="1"></property>
<property name="name" value="zhangsan"></property>
<property name="age" value="20"></property>
<property name="gender" value="男"></property>
</bean>
</beans>
3、测试类:
package com.msb.test;
import com.msb.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//读取bean中配置文件
/**
* applicationContext:表示IOC容器的入口,想要获取对象的话就必须创建该类
* 该类有两个实现配置文件的实现类
* ClassPathXmlApplicationContext:从classpath中读取数据
* FileSystemXmlApplicationContext:从当前文件系统读取数据
*/
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
//获取具体的bean对象,需要强制类型装换
Person person = (Person) context.getBean("person");
System.out.println(person);
}
}