首页 > 编程语言 > 详细

Spring配置步骤

时间:2017-07-15 18:37:43      阅读:332      评论:0      收藏:0      [点我收藏+]

1、导入spring的dist中的jar包和commons-logging包


2、在src目录下创建相应的beans.xml


3、为beans.xml添加相应的schema
<beans xmlns="http://www.springframework.org/schema/beans"
       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-3.0.xsd">      
</beans>


4、新建一个类

package org.test.spring.model;

public class HelloWorld {
    public String hello() {
        return "hello world";
    }
}


5、在beans.xml中创建对象
    <!--
    创建如下bean等于完成了:HelloWorld helloWorld = new HelloWorld

    scope 如果没有设置为单例模式,如果为prototype则为双例模式
     -->
    <bean id="helloWorld" class="org.zttc.itat.spring.model.HelloWorld" scope="prototype"/>

  
6、在测试类中使用这个对象
  6.1、创建Spring的工厂
      private BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
  6.2、通过Spring工厂获取相应的对象
    //此处getBean中的helloWorld就是beans.xml配置文件中的id
    HelloWorld hello = factory.getBean("helloWorld",HelloWorld.class);
    //此时的hello对象就是被Spring说管理的对象
    System.out.println(hello.hello());

Spring配置步骤

原文:http://www.cnblogs.com/andypengyong/p/7183699.html

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