首页 > 编程语言 > 详细

小试牛刀 spring的HelloWorld

时间:2014-12-06 11:12:35      阅读:245      评论:0      收藏:0      [点我收藏+]

先导入包:

commons-logging-1.1.1.jar  : spring依赖的包;

spring-beans-4.0.0.RELEASE.jar;

spring-context-4.0.0.RELEASE.jar;

spring-core-4.0.0.RELEASE.jar;

spring-expression-4.0.0.RELEASE.jar;

 

bubuko.com,布布扣
 1 package com.model;
 2 
 3 public class HelloWorld {
 4 
 5     private String username;
 6 
 7     public void setUsername(String username) {
 8         this.username = username;
 9     }
10     
11     public void hello(){
12         System.out.println("hello:"+username);
13     }
14     
15 }
View Code
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <bean id="hello" class="com.model.HelloWorld">
 7         <property name="username" value="spring4"></property>
 8     </bean>
 9 
10 
11 </beans>
 1 package com.model;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Main {
 7 
 8     public static void main(String[] args) {
 9         //获取spring的IOC容器
10         ApplicationContext ac = new ClassPathXmlApplicationContext("hello.xml");
11         
12         //从容器中获取bean;hello对于xml文件中bean的id
13         HelloWorld helloWorld = (HelloWorld) ac.getBean("hello");
14         System.out.println(helloWorld);
15         //调用方法
16         helloWorld.hello();
17     }
18     
19 }

打印结果:

十二月 06, 2014 9:51:47 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1642bd6: startup date [Sat Dec 06 09:51:47 CST 2014]; root of context hierarchy
十二月 06, 2014 9:51:47 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [hello.xml]
com.model.HelloWorld@154ab89
hello:spring4

小试牛刀 spring的HelloWorld

原文:http://www.cnblogs.com/yzdqxing/p/4147895.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!