学习Spring的第一个HelloWorld

1 配置Spring

新建一个java工程,导入如下包:
Libraries

2 开始Spring编程

1 新建一个HelloWorld.java

package test;
public class HelloWorld {
    private String info ;
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }

}

2 编写配置文件applicationContext.xml
在当前工程下创建一个xml文件,添加如下代码

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    
    <!-- 配置需要被Spring管理的Bean(创建,创建后放在了Spring IOC容器里面)-->  
    <bean id="hello" class="test.HelloWorld">  
        <!-- 配置该Bean需要注入的属性(是通过属性set方法来注入的) -->  
        <property name="info" value="Hello World!"/>  
    </bean>  
</beans>  

3 反转控制开始
在Main.java中添加如下:

package test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
    public static void main(String[] args) {
        //获取Spring的ApplicationContext配置文件,注入IOC容器中  
        //(Map: key:String, bean标签的id属性值 ==>value:Object, bean标签class属性所指类的实例)  
        BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*
        HelloWorld hw1 = new HelloWorld();
        hw1.setInfo("Hello World!");
        */
        //Spring相当于如上代码,通过getBean获取xml文件中对应id值的Bean,在xml文件中配置该Bean需要注入的属性
        //不需要自己new对象以及赋值.
        HelloWorld hw1 = (HelloWorld)factory.getBean("hello");//map.get("hello")  
        System.out.println(hw1.getInfo());  
        System.out.println(hw1);  
    }
}

3 测试结果
result

3 总结

Spring可以通过配置的方法取得对象,而不再用new的方法来取得对象
* 先在xml配置文件中配置bean标签,如:

  <bean id="hello" class="test.HelloWorld">  
        <!-- 配置该Bean需要注入的属性(是通过属性set方法来注入的) -->  
        <property name="info" value="Hello World!"/>  
    </bean>  

其中
id 为bean的key,通过之后getBean()取得配置的Bean.
class 为创建的类所在包+类名
property标签为该Bean配置注入的属性.

  • 反转控制

1 通过

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");

来获取配置文件
2 通过getBean获取xml文件中对应id值的Bean,就可以取得我们想要得到的对象了.

学习自:http://blog.csdn.net/evankaka

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值