閱讀709 返回首頁    go iPhone_iPad_Mac_apple


SPRING-HELLOWORLD 改寫為構造注入

1.helloworld類增加構造方法

2.改寫配置文件config.xml

3.測試程序testhelloworld.java


1.增加構造方法,MSG作為參數

package com.gc.action;

public class HelloWorld {

	public String msg=null;//該變量用來存儲字符串
	
	//增加了一個構造方法
	public HelloWorld(String msg) {
		this.msg=msg;
	}
	
	//設定變量msg的set方法
	public void setMsg(String msg) {
		this.msg=msg;
	}
	
	//獲取變量msg的get方法
	public String getMsg() {
		return this.msg;
	}
	
}

2.config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"https://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <!--定義一個Bean-->
    <bean  >
    <!--通過構造函數進行注入-->
    <constructor-arg index="0">
        <value>nihao</value>
    </constructor-arg>
    </bean>
</beans>

3.測試程序

package com.gc.test;

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

import com.gc.action.HelloWorld;

public class TestHelloWorld {
    public static void main(String[] args)
    {
    	//通過ApplicationContext來獲取Spring文件的配置
    	ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");
    
        //通過Bean的id來獲取Bean
    	HelloWorld HelloWorld=(HelloWorld)actx.getBean("HelloWorld");
    	
    	//打印輸出
    	System.out.println(HelloWorld.getMsg());
    }
}

輸出:


nihao




最後更新:2017-04-02 22:16:38

  上一篇:go android 係統日誌Logcat 完全捕獲
  下一篇:go 講得非常詳盡的c++經典高清視頻教程打包下載!個人感受很深