step1:
在package:pojo下建立Category类,用来作为操作对象:
代码:
package com.how2java.pojo;
public class Category {
private int id; //定义变量id;
private String name;//定义变量name;
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; }
//定义setter和getter;}
step2:
建立Spring核心配置文件applicationContext:代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"<!--xml name space/xml命名空间;初始化bean的格式文档地址-->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!-- xml所遵守的标签规范;辅助初始化bean-->
xmlns:aop="http://www.springframework.org/schema/aop"
<!-- 辅助建立aop/面向切面编程-->
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
<!-- Spring上下文,包括资源加载文件-->
xsi:schemaLocation=" <!--声明了目标命名空间的模式文档--> http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="c" class="com.how2java.pojo.Category"> <property name="name" value="category 1" /> </bean> <!-- 初始化category类,关键字为"c",变量"name"注入属性"caterogy 1"--></beans>
step3:
实际获取对象:
package com.how2java.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.how2java.pojo.Category;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
//加载配置文件;
Category c = (Category) context.getBean("c");
//获取对象c:Category;
System.out.println(c.getName());
}
}
step4:通过ref 注入对象:
<bean name="p" class="com.how2java.pojo.Product">创建对象p:product;
<property name="name" value="product1" />属性name注入product 1;
<property name="category" ref="c" /> 属性category注入对象Category;
</bean>