Spring第一天 入门
1.Spring的IOC理解。
2.编写Spring的程序:
1)引入Spring相关的jar包。(可以从官网下载,下载之后将lib下的jar包拷贝到项目中,另外一种方式是通过myeclipse去完成…..)
2)编写applicationContext.xml配置文件(将java的对象注入到IOC容器里)。比如:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
//
3.在Spring中如何注入一个对象?
分类:
1)set注入(属性注入)。(无参构造函数)
<bean id="fan" class="com.model.Woman">
<property name="name" value="范冰冰" ></property>
<property name="age" value="32" ></property>
<property name="type" value="女神" ></property>
</bean>
2)构造函数的注入:
<bean id="liu" class="com.model.Woman">
<constructor-arg value="刘亦菲" name="_name" type="java.lang.String"></constructor-arg>
<constructor-arg value="30" name="_age" type="int"></constructor-arg>
<constructor-arg value="美女" name="_type" type="java.lang.String"></constructor-arg>
</bean>
3)匹配bean对象 ref元素是用在property中,来设置需要引用的容器管理的其它Bean。
<bean id="li" class="com.model.Man">
<property name="name" value="李晨"></property>
<property name="fan" ref="fan"></property>
</bean>
</beans>
测试:第3个
package com.UI;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.model.Man;
import com.model.Woman;
public class TextUI {
public static void main(String[] args){
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//Woman woman=appContext.getBean("li",Woman.class);
Man man=appContext.getBean("li",Man.class);
System.out.println("姓名:"+man.getName()+"女朋友的名字:"+man.getFan().getName());
}
}