Spring(4)--- hello world实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangbijun1230/article/details/85532601

Spring hello world实例

本教程介绍如何在Spring4 中创建一个简单的 Hello World 例子。

在这篇文章中使用的技术或工具:

  1. Spring 4.1
  2. Eclipse 10
  3. JDK 1.8

项目文档结构:创建MAVEN 项目

 

pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.javass.spring.chapter2</groupId>
  <artifactId>HelloSpring1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <dependencies>
 
        <!-- Spring Core -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
         
        <!-- Spring Context -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
             
    </dependencies>
</project>

Beans 文件

<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.xsd">
  
    <bean id="helloBean" class="com.zyzx.core.HelloWorld">
        <property name="name" value="zyzx" />
    </bean>
  
</beans>

执行文件

package com.zyzx.core;

/**
 * Spring bean
 * 
 */
public class HelloWorld {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void printHello() {
        System.out.println("Spring 4 : Hello ! " + name);
    }
}

package com.zyzx.core;

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

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "beans.xml"); 
        HelloWorld obj = (HelloWorld) context.getBean("helloBean");
        obj.printHello();
    }
}

输出结果:

Spring 4 : Hello ! zyzx

猜你喜欢

转载自blog.csdn.net/zhangbijun1230/article/details/85532601