Spring学习(一)——构建第一个spring程序

首先在eclipse上建立maven项目,关于建立方式,网上有许多教程,这里就不在赘述

在pom.xml中添加以下依赖:

  
      org.springframework
      spring-context
      5.0.7.RELEASE
      runtime
  

version中的RELEASE需要带上,不然会报错(版本名称不完整)

 

项目结构如下:

Spring学习(一)——构建第一个spring程序_第1张图片

 

firstbean:

package com.springdemo;

public class firstbean {

	private String something;

	public String getSomething() {
		return something;
	}

	public void setSomething(String something) {
		this.something = something;
	}	
}

secondBean:

package com.springdemo;

public class secondBean {
	private String something;
	
	public String getSomething() {
		return something;
	}
	
	public void setSomething(String something) {
		this.something=something;
	}
}

thirdbean:

package com.springdemo;

public class thirdbean {

	private firstbean first;
	private secondBean second;
	private int index;
	private String type;

	public firstbean getFirst() {
		return first;
	}

	public void setFirst(firstbean first) {
		this.first = first;
	}

	public secondBean getSecond() {
		return second;
	}

	public void setSecond(secondBean second) {
		this.second = second;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
}

App:

public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = new ClassPathXmlApplicationContext("springdemo.xml");
    	firstbean demo=(firstbean)context.getBean("firstbean");
    	demo.setSomething("I'm firstbean");
    	
    	secondBean demo2=(secondBean)context.getBean("secondbean","com.springdemo.secondBean");
    	demo2.setSomething("I'm secondbean");
    	
    	thirdbean demo3=(thirdbean)context.getBean("thirdbean","com.springdemo.thirdbean");
    	System.out.println(demo3.getFirst().getSomething());
    	System.out.println(demo3.getSecond().getSomething());
    	System.out.println(demo3.getIndex());
    	System.out.println(demo3.getType());
    	
    }
}

springdemo.xml:



       



	
	
	
	

执行结果:

 

遇到的异常:

parsing XML document from class path resource [springdemo.xml]

原因是xml文件应该放在src目录下,否则需要指明xml'文件的路径

 

通过上面这个例子,可以看出默认情况下spring的bean的scope为singleton

你可能感兴趣的:(spring)