Spring的第一個例子,Spring第一個例子

來源:互聯網
上載者:User

Spring的第一個例子,Spring第一個例子

Spring 的控制翻轉IoC,或者依賴注入。在測試類別中沒有new一個新對象,對象是從xml檔案中注入的。

xml檔案中的<beans>是一個大容器,裡面的<bean>就是容器裡面的內容,這些內容是一個一個的執行個體對象。

我們把對象建立在了xml檔案中,所以就不用再在Java中建立對象了,當我們使用這些對象的時候,就從xml的bean注入即可。

1.建立類

package com.wangcf;public class HelloWorld {    private String name;    public void sayHello(){        System.out.println("Hello World"+name);    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

2.建立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"     xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"    >    <!-- 註冊一個Hello World,執行個體名稱為HelloWorld -->    <bean name="helloworld" class="com.wangcf.HelloWorld">        <property name="name">            <value>小明</value>        </property>    </bean></beans>

3.建立測試類別

package com.wangcf;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class HelloTest {    @Test    public void testSayHello() {        //建立Spring 容器        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");        //從容器中得到一個bean,也就是一個執行個體對象        HelloWorld hello=(HelloWorld)context.getBean("helloworld");        hello.sayHello();    }}

4.輸出結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.