Spring自从有了注解,就不需要在application.xml中写<bean>组件了。
@component("xxx")表示这是一个Spring Bean,可以直接通过Spring容器创建对象;
@Autowired表示自动注入一个对象;
@Resource和@Autowired差不多。只不过多声名了一个Spring Bean的名称。
package com.zai.pojo;
import org.springframework.stereotype.Component;
@Component("c")
public class Category {
private int id;
private String name = "xiao";
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;
}
}
package com.zai.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.DecimalFormat;
@Component("g")
public class Goods {
private String name;
private DecimalFormat price;
@Resource(name = "c")
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DecimalFormat getPrice() {
return price;
}
public void setPrice(DecimalFormat price) {
this.price = price;
}
}
package com.zai.test;
import com.zai.pojo.Category;
import com.zai.pojo.Goods;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Goods goods = (Goods) context.getBean("g");
System.out.println(goods.getCategory().getName());
}
}
xiao