• Spring入门示例


    开发环境

      Spring 4.3.0+Myeclipse2015+JDK1.8

    准备阶段:

      1、新建一Spring01项目,然后新建一个lib文件。将下面的添加到lib文件中

      2、将lib文件所有的包导入项目

    开发步骤:

      1、新建一个Hello.java的类

     1 package com.proc.bean;
     2 
     3 public class Hello {
     4 
     5     private String msg;
     6 
     7     public void setMsg(String msg) {
     8         this.msg = msg;
     9     }
    10     public void say(){
    11         System.out.println("Hello "+msg);
    12     }
    13 }

      2、在src文件夹下面新建一个applicationContext.xml文件

     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
     5         http://www.springframework.org/schema/beans/spring-beans.xsd">
     6         <!-- id:该实例的名称,class:该实例的类型 -->
     7         <bean id="helloWorld" class="com.proc.bean.Hello">
     8             <!-- 设置属性msg的值为world -->
     9             <property name="msg" value="world"></property>
    10         </bean>
    11 </beans>

      3、代码测试

     1 package com.proc.test;
     2 
     3 import org.junit.Test;
     4 import org.springframework.context.ApplicationContext;
     5 import org.springframework.context.support.ClassPathXmlApplicationContext;
     6 
     7 import com.proc.bean.Hello;
     8 
     9 public class TestSpring {
    10     
    11     @Test
    12     public void test1(){
    13         ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    14         Hello hello=(Hello)context.getBean("helloWorld");
    15         hello.say();
    16     }
    17 }

      

      结果输出:

    六月 23, 2016 3:23:13 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
    信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1637f22: startup date [Thu Jun 23 15:23:13 CST 2016]; root of context hierarchy
    六月 23, 2016 3:23:13 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    信息: Loading XML bean definitions from class path resource [applicationContext.xml]
    Hello world
  • 相关阅读:
    Socket的应用案例
    利用XStream实现对象XML话
    策略模式
    深入理解Java引用类型
    java 消息机制 ActiveMQ入门实例
    activity工作流表结构分析
    Spring MVC 之 Hello World
    如何发布Web项目到互联网
    ionic开发ios app
    ionic开发android app步骤
  • 原文地址:https://www.cnblogs.com/caoyc/p/5610962.html
Copyright © 2020-2023  润新知