spring中的init-method的不解

wang19841229 2007-07-25 11:35:50
我有两个类都实现了Ijiaotong接口
代码如下
第一个类
package com.springtest;

public class Car implements Ijiaotong {
private String name;
private Ipeople ipeople;
public Ipeople getIpeople() {
return ipeople;
}
public void setIpeople(Ipeople ipeople) {
this.ipeople = ipeople;
}
public void init()
{
System.out.println("初始化");
}

public void kai()
{
ipeople.fly();
System.out.println( "开动");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第二个类
package com.springtest;

public class Plane implements Ijiaotong {
private String name;
private Ipeople ipeople;

public Ipeople getIpeople() {
return ipeople;
}
public void setIpeople(Ipeople ipeople) {
this.ipeople = ipeople;
}
public String getName() {
return name;
}
public void init2()
{
System.out.println("初始化");
}

public void setName(String name) {
this.name = name;
}


public void kai() {
ipeople.fly();
System.out.println(name + "开动");
}

}
接口:
package com.springtest;

public interface Ijiaotong {

public void kai();


}
spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans default-autowire="byName">
<bean id="ipeople" class="com.springtest.People"></bean>
<bean id="car" class="com.springtest.Car" init-method="init">
</bean>
<bean id="plane" class="com.springtest.Plane" init-method="init2">
</bean>

</beans>
程序的入口点类
package com.springtest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(
"src/applicationContext.xml");
System.out.println(applicationContext);
Ijiaotong jiaotong = (Ijiaotong) applicationContext.getBean("car");
jiaotong.kai();

}
}
我不明白:我只是用spring实例化了一个car类的对象为什么两个类的init方法都调用了

输出结果:

初始化
初始化
人类
开动


...全文
2572 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuzq819 2007-08-01
  • 打赏
  • 举报
回复
<bean id="plane" class="com.springtest.Plane" init-method="init2">

你把 init-method="init2" 去掉就不会执行了~

你为什么要研究它呢?

配置文件很重要啊!
鑫鑫_ 2007-08-01
  • 打赏
  • 举报
回复
<bean id="plane" class="com.springtest.Plane" init-method="init2">

你把 init-method="init2" 去掉就不会执行了~

你为什么要研究它呢?
wang19841229 2007-07-29
  • 打赏
  • 举报
回复
那为什么plane类的INIT方法也执行了
鑫鑫_ 2007-07-26
  • 打赏
  • 举报
回复
在你初始化car类之前,spring会自动的为执行car下的init方法 感觉有点类似于静态方法

并且你的xml也是这么设置的:
<beans default-autowire="byName">
<bean id="ipeople" class="com.springtest.People"></bean>
<bean id="car" class="com.springtest.Car" init-method="init">
</bean>
<bean id="plane" class="com.springtest.Plane" init-method="init2">
</bean>

</beans>

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧