zoukankan      html  css  js  c++  java
  • 小试牛刀 spring的HelloWorld

    先导入包:

    commons-logging-1.1.1.jar  : spring依赖的包;

    spring-beans-4.0.0.RELEASE.jar;

    spring-context-4.0.0.RELEASE.jar;

    spring-core-4.0.0.RELEASE.jar;

    spring-expression-4.0.0.RELEASE.jar;

     1 package com.model;
     2 
     3 public class HelloWorld {
     4 
     5     private String username;
     6 
     7     public void setUsername(String username) {
     8         this.username = username;
     9     }
    10     
    11     public void hello(){
    12         System.out.println("hello:"+username);
    13     }
    14     
    15 }
    View Code
     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 http://www.springframework.org/schema/beans/spring-beans.xsd">
     5 
     6     <bean id="hello" class="com.model.HelloWorld">
     7         <property name="username" value="spring4"></property>
     8     </bean>
     9 
    10 
    11 </beans>
     1 package com.model;
     2 
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.support.ClassPathXmlApplicationContext;
     5 
     6 public class Main {
     7 
     8     public static void main(String[] args) {
     9         //获取spring的IOC容器
    10         ApplicationContext ac = new ClassPathXmlApplicationContext("hello.xml");
    11         
    12         //从容器中获取bean;hello对于xml文件中bean的id
    13         HelloWorld helloWorld = (HelloWorld) ac.getBean("hello");
    14         System.out.println(helloWorld);
    15         //调用方法
    16         helloWorld.hello();
    17     }
    18     
    19 }

    打印结果:

    十二月 06, 2014 9:51:47 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1642bd6: startup date [Sat Dec 06 09:51:47 CST 2014]; root of context hierarchy
    十二月 06, 2014 9:51:47 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [hello.xml]
    com.model.HelloWorld@154ab89
    hello:spring4

  • 相关阅读:
    《2019年软件工程助教培训计划》
    地铁线路项目-结对编程
    预培训-个人项目(地铁线路规划)
    粗读《构建之法》后的问题
    netapp 修改IP地址
    jump server 2.6.1 安装与配置
    CCNA-实验1-Manage_IOS
    系统结构综合实践期末大作业 第22组
    2017级系统综合实践第7次实践作业 01组
    2017级系统综合实践第6次实践作业 01组
  • 原文地址:https://www.cnblogs.com/yzdqxing/p/4147895.html
Copyright © 2011-2022 走看看