本帖最后由 sadfoo2019 于 2021-3-2 01:07 编辑
问题:初学spring,搞个配置半天没对,求指点哪里有问题?
bean
[Java] 纯文本查看 复制代码 public class Category {
private String name;
private int id;
/**
* [url=home.php?mod=space&uid=155549]@Return[/url] the name
*/
public String getName() {
return name;
}
/**
* [url=home.php?mod=space&uid=952169]@Param[/url] name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
[Java] 纯文本查看 复制代码 public class Product {
private int id;
private String name;
/*
* 在Product.java的category属性前加上@Autowired注解
*/
@Autowired
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;
}
}
Spring的XML文件配置内容
[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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
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">
<context:annotation-config>
<!-- 配置 -->
<bean name="c" class="com.gg.pojo.Category">
<property name="name" value="Category 1"></property>
</bean>
<!-- 在创建Product的时候注入一个Category对象;注意:这里要使用REF来注入另一个对象 -->
<bean name="p" class="com.gg.pojo.Product">
<property name="name" value="Product 1"></property>
<!-- <property name="category" ref="c"></property> -->
</bean>
</context:annotation-config>
</beans>
测试类
[Java] 纯文本查看 复制代码 public class TestSpring_2 {
/**
* Title: main Description:
*
* @param args
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
// 解析XML文件
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
Product product = (Product) ac.getBean("p");
System.out.println(product.getName());
System.out.println(product.getCategory().getName());
}
} |