Spring init方法

时间:2015-08-10 04:51:30

标签: java spring

我学习了春天,我在init,destroy方法和构造函数部分中感到困惑

这是public class Car { private Engine engine; public Car(Engine engine){ System.out.println("Inside Car constructor"); this.engine = engine; } public void startCarEngine(){ engine.startEngine(); } private void initEngine(){ System.out.println("heating up engine"); } }

Engine.java

这是public class Engine { public Engine(){ System.out.println("Inside Engine constructor"); } public void startEngine(){ System.out.println("Engine is starting..."); } }

MessageBean.java

这是public class MessagesBean { private static final String HELLO_WORLD = "Hello World"; public MessagesBean(){ System.out.println("Printing " + HELLO_WORLD); } public void start(){ System.out.println("Step 2.Bean is starting"); } }

Main class

这是 AbstractApplicationContext abstractAppContext = new ClassPathXmlApplicationContext("spring-config.xml"); MessagesBean msgBean2 = abstractAppContext.getBean("msgBean", MessagesBean.class);

output

这是我的 Printing Hello World Step 2.Bean is starting Inside Engine constructor Inside Car constructor heating up engine

MessageBean

这是我的MessageBean Constructor

init

我的问题是我在主课程中只调用<tr> <td>Down payment $</td> <td> <input name="downpaymentpc" id="downpaymentpc" type="text" size="8" maxlength="8" onChange="javascript:downPaymentPcChanged(true);" value="<?php echo $min_fha_down_payment;?>" />%</td> <td colspan="2">Or $ <input name="downpaymentamt" id="downpaymentamt" type="text" size="8" maxlength="8" onChange="javascript:downPaymentAmountChanged(true);" /> </td> </tr> 并且它应该只调用<div class="col-md-2 padding-Zero"> <input name="downpaymentpc" id="downpaymentpc" type="text" class="txt" size="8" maxlength="8" onChange="javascript:downPaymentPcChanged(true);" value="<?php echo $min_fha_down_payment;?>" /> </div> <div class="col-md-1 padding-lft"> <img src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer" /> </div> <td>Monthly MIP </td> <td> <input name="monthlymippc" type="text" size="8" maxlength="8" onChange="javascript:monthlyMIPPcChanged(true)" /> %</td> <td>Or $ <input name="monthlymipamt" type="text" size="8" maxlength="8" onChange="javascript:monthlyMIPAmountChanged(true)"/> </td> 方法,但为什么另外两个bean构造函数和init方法是叫做或做错了什么?如果我对不同的bean有不同的init,destroy方法,并且我只想初始化/调用特定的bean(s)构造函数和init方法,该怎么办?

1 个答案:

答案 0 :(得分:2)

默认情况下,spring beans会被急切地初始化,如果你想让它们懒得初始化,可以在bean定义中添加这个属性

lazy-init="true"