Spring初体验

java开发4年经验,现在才在项目中真正用上Spring,惭愧。

1 生成目录结构

IDEA生成工程目录机构和pom.xml:

File-> New -> Project…->Maven -> 勾选Create from archetype -> org.apache.camel.archetypes:maven-archetype-quickstart -> Next ->

Spring初体验_第1张图片

生成的目录结构(除了resources目录和java文件)如下:

springlearn
    |─pom.xml
    |─src
        |─main
        |   |─java
        |       |-indi.zhb
        |               |-Quest.java
        |               |-SlayDragonQuest.java
        |               |-Knight.java
        |               |-BraveKnight.java
        |               |-App.java
        |
        |   |─resources
        |       |─spring.xml
        |
        |─test
            |─java

2. pom.xml

生成的pom.xml如下:


  4.0.0

  indi.zhb
  springlearn
  1.0-SNAPSHOT
  jar

  springlearn
  http://maven.apache.org

  
    UTF-8
  

  
    
      junit
      junit
      3.8.1
      test
    

  

参考官方文档https://projects.spring.io/spring-framework/ ,加入spring依赖:


    org.springframework
    spring-context
    4.3.9.RELEASE

代码内容(改自Spring in action第一章)

Quest.java

package indi.zhb;

/**
 * Created by huabinzheng on 2017/6/26.
 */
public interface Quest {
    void embark();
}

SlayDragonQuest.java

package indi.zhb;

import java.io.PrintStream;

/**
 * Created by huabinzheng on 2017/6/26.
 */
public class SlayDragonQuest implements Quest {
    private PrintStream stream;
    public SlayDragonQuest(PrintStream stream) {
        this.stream = stream;
    }

    public void embark() {
        stream.println("Embarking on quest to slay the dragon!");
    }
}

Knight.java

package indi.zhb;

/**
 * Created by huabinzheng on 2017/6/26.
 */
public interface Knight {
    public void embarkOnQuest();
}

BraveKnight.java

package indi.zhb;

/**
 * Created by huabinzheng on 2017/6/26.
 */
public class BraveKnight implements Knight {
    private Quest quest;

    public BraveKnight(Quest quest) {
        this.quest = quest;
    }

    public void embarkOnQuest() {
        quest.embark();
    }
}

App.java

package indi.zhb;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App 
{
    public static void main( String[] args )
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        BraveKnight knight = context.getBean(BraveKnight.class);
        knight.embarkOnQuest();
        context.close();
    }
}

Spring配置文件

用IDE来生成配置文件框架:右击resources-> New -> XML Configuration File -> Spring Config,取名为spring.xml,内容如下,





往xml文件添加bean:


    



    

你可能感兴趣的:(Spring初体验)