• Spring学习——Hello World


    开发环境jdk1.6,spring 3.0.2,spring tool suit。

    1.新建一个java工程,在lib中加入如下jar包

    2.写一个HelloWorld类,写一个sayHello()方法。

    package com.mydomain

    public class HelloWorld {
    public
    void sayHello(){
    System.out.println(
    "Hello World!");
    }
    }

    3.类路径中创建bean配置文件bean.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"
    xsi:schemaLocation
    ="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    >

    <bean name="helloWorld" class="HelloWorld"></bean>

    </beans>

    4.写一个Main类测试HelloWorld.在这里用到用到接口ApplicationContext和ClassPathXmlApplicationContext。

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

    public class Main {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
    HelloWorld hello
    = (HelloWorld)context.getBean("helloWorld");
    hello.sayHello();
    }

    }

    ApplicationContext是一个bean factory,可以存放各种bean和bean dependencies的注册。

    ClassPathXmlApplicationContext是ApplicationContext的一个实现。

    getBean(Stringname)取得配置的实例.然后调用方法sayHello().

    5.运行程序。输出结果:

    Hello World!

    从控制台可以看到一些信息如下: 

    代码
    2010-6-5 21:51:55 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@758fc9:
     startup date [Sat Jun
    05 21:51:55 CST 2010]; root of context hierarchy
    2010-6-5 21:51:56 org.springframework.beans.factory.xml.XmlBeanDefinitionReader
    loadBeanDefinitions
    信息: Loading XML bean definitions from
    class path resource [bean.xml]
    2010-6-5 21:51:57 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    信息: Pre
    -instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ef5502:
    defining beans [helloWorld]; root of factory hierarchy
    Hello World
    !
  • 相关阅读:
    WINNER队成立(第二天)
    新学期组队合作
    构建之法第8、9、10章
    第一阶段冲刺(第一天)
    作业六:小学生四则运算之NABCD模型与产品Backlog。
    构建之法第六章、第七章观后感
    四则运算,测试与封装。
    使用Webpack4 搭建React项目
    算法一小时--希尔排序
    算法一小时-插入排序
  • 原文地址:https://www.cnblogs.com/goodwin/p/1752439.html
Copyright © 2020-2023  润新知