spring实践(一)
1 创建项目结构
2 Hello类
package younghd;
public class Hello {
private String name;
private String id;
public String getName() {
return name;
}
public Hello() {
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Hello(String id,String name) {
this.name = name;
this.id = id;
}
}
3 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 = "chinese" class="younghd.Hello">
<property name="id" value="中文"/>
<property name="name" value="你好"/>
</bean>
<bean id = "english" class="younghd.Hello">
<property name = "id" value="英语"/>
<property name = "name" value="hello"/>
</bean>
<bean id="korea" class="younghd.Hello">
<constructor-arg value="韩国"></constructor-arg>
<constructor-arg value="撒狼嘿呦"></constructor-arg>
</bean>
</beans>
4 测试类
package younghd;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("强制转换: ");
Hello hello1 = (Hello)ac.getBean("chinese");
System.out.println(hello1.getId()+":"+hello1.getName());
System.out.println("类的反射: ");
Hello hello2 = ac.getBean("english",Hello.class);
System.out.println(hello2.getId()+":"+hello2.getName());
System.out.println("构造函数");
Hello hello3 = ac.getBean("korea",Hello.class);
System.out.println(hello3.getId()+":"+hello3.getName());
}
}
5 结果展示
6 体会
1.普通的java程序创建对象,是通过new方法实现,对象需要我们自己管理
2. Spring的java程序,对象是由Spring管理,当我们需要某个对象时,就通过Spring容器获取对象的实例
3. Spring的id可以认为是bean的标识符,是唯一的