spring 第一个程序 hello

来源:互联网 发布:uml类图转化为java代码 编辑:程序博客网 时间:2024/05/18 01:47


public class HelloWord {
 private String userName;


public void setUserName(String userName) {
this.userName = userName;
}
public void hello(){
System.out.println("hello:"+userName);
}
 
}


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


public class Test {
public static void main(String[] args) {
/**
* 创建对象及为对象赋值交给spring完成
*/
// HelloWord helloWord = new HelloWord();
// helloWord.setUserName("hello");
// helloWord.hello();

//1.创建spring IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");


//2从容器中获得Bean
HelloWord helloWord = (HelloWord) ctx.getBean("helloWord");


//3.调用方法
helloWord.hello();
}
}

配置文件为:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置bean -->
<bean id="helloWord" class="com.spring.HelloWord">
 <property name="userName" value="springsss"></property>
</bean>


</beans>


输出结果为:

hello:springsss

0 0