Spring-2,helloworld

Spring HelloWorld

使用Spring:

1.創建一個java工程

2.添加jar包
這裏寫圖片描述

3.創建一個類(Helloworld.java)

package com.tuxianchao.spring.beans;

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

public class HelloWorld {
    private String name;

    public HelloWorld() {
        System.out.println("HelloWorld's Constructor...");
    }

    public void setName(String name) {
        System.out.println("HelloWorld's setName..");
        this.name = name;
    }

    public void hello() {
        System.out.println("hello:" + name);
    }

    public static void main(String[] args) {
        // 沒有使用Spring的時候:
        // // 1.創建一個helloworld對象
        // helloWorld helloWorld = new helloWorld();
        // // 2.爲對象的屬性賦值
        // helloWorld.setName("spring");
        // // 3.使用對象的方法
        // helloWorld.hello();

        // 使用spring
        // 1.創建spring的IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 2.從容器中獲取bean實例
        HelloWorld helloWorld = (com.tuxianchao.spring.beans.HelloWorld) ctx.getBean("helloworld");
        // HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
        // 3.使用對象方法
        helloWorld.hello();
    }
}

4.在類路徑下建立spring的配置文件(ApplicationContext.xml)

5.在配置文件中配置bean

<?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.xsd">


    <!-- 配置bean -->
    <bean id="helloworld" class="com.tuxianchao.spring.beans.HelloWorld">
        <property name="name" value="Spring"></property>
    </bean>
</beans>

運行結果:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章