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" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!--定义一个Bean--> <bean id="HelloWorld" class="com.gc.action.HelloWorld"> <!--通过构造函数进行注入--> <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