Java架構之Spring(二)

來源:互聯網
上載者:User

標籤:classpath   3.1   附加   framework   根據   ica   action   eclips   public   

前一篇部落格講述了Spring的一些基礎概念,下面我們來建立第一個Spring程式吧。

步驟如下:

1) 導包

2) 設定檔

附沒有提示的情況 

MyEclipse ->File and Editors -XML ->XML Catlog, 點擊 add,找到上面的檔案 spring-beans-3.1.xsd,然後 Key type 選 SchemaLoaction, key 後面加上 spring-beans-3.1.xsd即可。

//beans.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:p="http://www.springframework.org/schema/p"      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">                  //這裡自己根據需要去設定,將UserInf這個類交給Spring管理       <bean name="userInfo_name" class="cat.beans.UserInfo" >      <property name="id" value="1" />      <property name="userName" value="趙明明" />      <property name="password" value="123" />      <property name="note" value="這是備忘" />      </bean>            </beans>
public class Test {    public static void main(String[] args) {    //初始化容器    ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");                        UserInfo user=(UserInfo) ctx.getBean("userInfo_name");//下面講解兩種等效方法                        /*可以這樣,條件是在beans.xml中只有一個userInfo_name的情況下。    *多了,就不能用這個了,因此推出可以用下面帶參數的方法    *UserInfo user=ctx.getBean(UserInfo.class);    */                        //帶參數的方法    //UserInfo user=ctx.getBean("userInfo_name", UserInfo.class);                        System.out.println(user);                        /*附加:初始化容器,也可以這樣寫    *ApplicationContext ctx= new ClassPathXmlApplicationContext("beans.xml");    *因為 ApplicationContext 是 ClassPathXmlApplicationContext的父類    */            }}

Java架構之Spring(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.