Spring是怎么自动装配的,我该怎么用,需要注意的点有哪些
package yinyong;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static Bean bean;
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Bean.xml");
bean = (Bean)applicationContext.getBean("zhuang_pei");
bean.getUser().Out();
bean = (Bean)applicationContext.getBean("name_zhuangpei");
System.out.println(bean.getUser());
}
}
package yinyong;
public class User {
private String name;
private Integer age;
private char sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public User(String name, Integer age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void Out() {
System.out.println("name: " + name);
System.out.println("age: " + age);
System.out.println("sex: " + sex);
}
public User() {
}
}
package yinyong;
public class Bean {
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Bean(User user) {
this.user = user;
}
public Bean() {
}
private User user;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" 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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<import resource="classpath:zhuru.xml"/>
<!-- 导入其它文件的配置 -->
<bean id="zhuang_pei" class="yinyong.Bean">
<property name="user" ref="zhuru_gouzao"></property>
<!-- 引用其它文件的bean -->
</bean>
<bean autowire="byName" id="name_zhuangpei" class="yinyong.Bean"></bean>
</beans>
先写个例子,我看下有什么区别
参考GPT和自己的思路:根据你提供的代码和问题描述,可能出现报错的地方是在 xml 文件中定义的自动装配方式。在你的 xml 文件中,通过设置 autowire="byName"
,表示按照名称自动装配。但是,你并没有在 xml 文件中给 name_zhuangpei
这个 bean 定义一个名为 user
的属性,所以当尝试获取 name_zhuangpei
这个 bean 时会报错。
要解决这个问题,你需要为 name_zhuangpei
这个 bean 添加一个名为 user
的属性,并指定它所依赖的 bean 的名称为 zhuru_gouzao
。代码如下:
<bean autowire="byName" id="name_zhuangpei" class="yinyong.Bean">
<property name="user" ref="zhuru_gouzao" />
</bean>
这样,当你在程序中调用 applicationContext.getBean("name_zhuangpei")
时,它就会自动装配依赖的 user
对象了。