标签:public 设置 one ota class poj 创建 category config
实体类Category
public class Category {
private int id;
private String 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;
}
}
实体类Product
public class Product {
private int id;
private String name;
private Category category;
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;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
通过
<bean name="c" class="com.how2java.pojo.Category">
<property name="id" value="category 1"/>
</bean>
<bean name="p2" class="com.how2java.pojo.Product" >
<property name="id" value="1"></property>
<property name="name" value="p"></property>
//引用类型
<property name="category" ref="c"></property>
</bean>
通过 p 命名空间 需要在applicationContext中增加命名空间
<bean name="c" class="com.how2java.pojo.Category" p:name="category 2">
//引用类型
<bean name="p" class="com.how2java.pojo.Product" p:name="product1" p:id="1" p:category-ref="c"></bean>
//首先需要在applicationContext.xml中增加
<context:annotation-config/>
<bean name="p" class="com.how2java.pojo.Product" >
<property name="id" value="1"></property>
<property name="name" value="p"></property>
</bean>
//这里并没有配置Category,但是测试中仍然成功,因为
public class Product {
private int id;
private String name;
@Autowired
private Category category;
public int getId() {
return id;
}
...}
这里设置为category 自动装配
@Autowired
public Category getCategory() {
return category;
}
也可以在setter方法上注入
@Resource //不一定是c
private Category category;
@Resource(name="c") //指定只能是 c
private Category category;
<context:component-scan base-package="com.how2java.pojo"/>//扫描包下的包,不需要xml配置
@Component("p")
public class Product {
private int id;
private String name;
@Resource
private Category category;
@Component("c")
public class Category {
private int id;
private String name;
//但是属性值为空
//设置<context:component-scan之后,能自动找到autowired装配的bean,不需要annotion-config了
标签:public 设置 one ota class poj 创建 category config
原文地址:https://www.cnblogs.com/zhuob/p/12288219.html