zoukankan      html  css  js  c++  java
  • 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
    !
  • 相关阅读:
    [功能发布]Excel与PowerBI互通互联升级版连接SSAS和AzureAS
    个人永久性免费-Excel催化剂功能第115波-word、pdf、Excel、ppt、html等文件互转
    个人永久性免费-Excel催化剂功能第113波-将帮助文档的主动权归还用户手中
    个人永久性免费-Excel催化剂功能第106波-重新定义使用Excel功能方式
    [功能发布]Excel催化剂2周年巨献-网页数据采集功能发布,满足90%合理场景使用
    Rabbitmq(一)
    Redis(三)
    MVC action过滤器验证登录
    分布式缓存 Redis(二)
    分布式缓存 Redis(一)
  • 原文地址:https://www.cnblogs.com/goodwin/p/1752439.html
Copyright © 2011-2022 走看看