添加依赖

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>



创建实体类

package cn.javaex.bean;

public class Person {
private String username;
private int age;
private String sex;
private String email;

public Person() {

}

public Person(String username, int age, String sex, String email) {
this.username = username;
this.age = age;
this.sex = sex;
this.email = email;
}

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "Person [username=" + username + ", age=" + age + ", sex=" + sex + ", email=" + email + "]";
}

}



创建 application.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">

<!-- 注册一个Person对象,spring会自动创建这个Person对象 -->
<!--
一个bean标签可以注册一个组件(对象、类)
id:这个对象的唯一标识
class:要注册的组件的全类名
-->
<bean id="person01" class="cn.javaex.bean.Person">
<!--
使用property标签为Person对象的属性赋值
name:指定属性名(属性名由get/set方法决定,建议自动生成,则就是成员变量名了)
value:为这个属性赋值
-->
<property name="username" value="张三"></property>
<property name="age" value="20"></property>
<property name="sex" value="男"></property>
<property name="email" value="291026192@qq.com"></property>
</bean>

<!-- 调用有参构造方法进行创建对象并赋值 -->
<bean id="person02" class="cn.javaex.bean.Person">
<constructor-arg name="username" value="李四"></constructor-arg>
<constructor-arg name="age" value="20"></constructor-arg>
<constructor-arg name="sex" value="女"></constructor-arg>
<constructor-arg name="email" value="291026192@qq.com"></constructor-arg>
</bean>
</beans>



测试

/**
* 从容器中拿到这个组件
*/
@Test
public void test01() {
/*
* 根据spring配置文件得到ioc容器对象
* ApplicationContext:代表ioc容器
* ClassPathXmlApplicationContext:当前应用的xml配置文件在classpath下
*
* 容器中对象的创建在容器创建完成的时候就已经创建好了
* 同一组件在ioc容器中是单例的
*/
ApplicationContext ioc = new ClassPathXmlApplicationContext("application.xml");

// 容器帮我们创建好对象了
Person bean1 = (Person) ioc.getBean("person01");
System.out.println(bean1);

Person bean2 = ioc.getBean(Person.class);
System.out.println(bean2);

System.out.println(bean1==bean2);
}



spring容器的启动流程




回到顶部