spring person
IOC: 由spring 进行创建、管理、配置
一个简单的例子
准配工作:导包
1、pojo实体类
package com.wt.pojo; public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } }
2、配置元数据
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- id 唯一变量名与实例化容器相呼应 class 为 实体类 property 为实体类的具体属性 value 为值 spring实现类的实例化和赋值 而不是通过传统的 new --> <bean id="person" class="com.wt.pojo.Person"> <property name="name" value="tom"/> </bean> </beans>
3、实例化容器
import com.wt.pojo.Person; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void showResult(){ ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml"); // person 对应配置文件的 id Person person = (Person) context.getBean("person"); String personString = person.toString(); System.out.println(personString); } }
new ClassPathXmlApplicationContext
idea快捷键 new CPX
注意:<property name="name" value="tom"/>
value 是普通变量
ref 指向自定义的类别名
例子
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="daoHello" class="com.wt.dao.UserDaoHello" /> <bean id="daoImp" class="com.wt.dao.UserDaoImp" /> <bean id="serviceImp" class="com.wt.service.UserServiceImp"> <property name="userDao" ref="daoHello" /> </bean> </beans>