Spring 学习笔记(三)—— bean配置之构造注入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m940034240/article/details/84990524

将HelloWorld类进行简单的修改

public class HelloWorld {
   
   private String message;
   private int num;

   public HelloWorld(String message, int num){
      this.message  = message;
      this.num = num;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
      System.out.println("Your Num : " + num);
   }
   
   public void init(){
      System.out.println("Bean is going through init.");
   }
   
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}

修改Beans.xml配置文件(注意class路径要根据你创建文件的位置修改):

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     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"
  >
  
  	<!--配置helloWorld实例,其实现类路径是demo.HelloWorld
		创建完成前调用该类的init()方法,销毁前调用该类的destroy()方法  -->
    <bean id="helloWorld" class="demo.HelloWorld" 
   		init-method="init" destroy-method="destroy">
   		<!--依次传入构造方法的参数  -->
        <constructor-arg value="hello"/>
        <constructor-arg value="222"/>
    </bean>
</beans>

下面进行测试

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");//配置文件的路径
      HelloWorld obj = context.getBean("helloWorld", HelloWorld.class);
      obj.getMessage();
      //为Spring容器注册关闭钩子
      ((AbstractApplicationContext) context).registerShutdownHook();
   }
}

运行以上代码,可以看到以下输出

Bean is going through init.
Your Message : hello
Your Num : 222
Bean will destroy now.

猜你喜欢

转载自blog.csdn.net/m940034240/article/details/84990524