1、创建Spring工程
使用eclipse创建一个Spring工程,一个简单的方法就是先创建一个Java工程,然后将Spring的Jar包全部放入到工程里面即可开始编写基于Spring框架的程序。Spring的Jar包可以从github上的源码中取得,下载地址是:https://github.com/spring-projects/spring-framework。
下面是在学习《Spring实战》时创建的一个Spring工程,其目录结构如下:
2、创建Bean
Spring的xml配置文件如下:
Spring的xml配置文件中xsd文件路径原本使用的网络路径,但是也可以使用本地的类库路径,因为在引入的spring包中spring-beans-3..*.RELEASE.jar中有spring-beans-3.0.xsd文件。
Bean配置文件中构造函数的参数顺序默认情况下必须与类定义中的参数顺序一致,也可以使用index(从0开始)属性来指定参数对应顺序。对于非基本类型,需要使用ref属性来引用其他bean。
对于Bean的创建,主要有三种方式:
http://my.oschina.net/itblog/blog/205172
1、构造器注入创建
对于有公共的构造方法的类(无论是默认的还是显示申明的构造方法),都可以使用构造器注入来创建为Bean
package lucien;
public class PoeticJuggler extends Juggler {
private Poem poem;
public PoeticJuggler(Poem poem) {
this.poem = poem;
}
public PoeticJuggler(int beanbags, Poem poem) {
super(beanbags);
this.poem = poem;
System.out.println("构造器注入创建PoeticJuggler");
}
public void perform() {
super.perform();
System.out.println("reciting...");
poem.recite();
}
}
2、工厂方法创建
对于没有公共构造方法的类,可以使用它的一个静态方法(无论该方法是private还是public,只要是static即可)来创建Bean。
package lucien;
public class Stage {
//私有的构造方法
private Stage() {
}
//静态的内部类
private static class StageSingletonHolder {
static Stage instance = new Stage();
}
//静态方法
public static Stage getInstance() {
System.out.println("工厂方法创建Stage");
return StageSingletonHolder.instance;
}
public void perform() {
System.out.println("Stage performance");
}
}
3、工厂类创建
使用工厂类的非静态方法(private和public均可,但必须是非static的)
package lucien;
public class Juggler implements Performer {
private int beanBags = 3;
public Juggler() {
}
public Juggler(int beanBags) {
this.beanBags = beanBags;
}
@Override
public void perform() {
// TODO Auto-generated method stub
System.out.println("JUGGLING " + beanBags + " BEANBAGS");
}
}
package lucien;
public class JugglerFactory {
public Juggler getJuggler() {
System.out.println("工厂类创建Juggler");
return new Juggler();
}
}
package lucien;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("ConfigFile.xml");
Performer performer = (Performer) ctx.getBean("poeticDuke");
performer.perform();
Stage stage = (Stage) ctx.getBean("stage");
stage.perform();
Juggler juggler = (Juggler) ctx.getBean("duke2");
juggler.perform();
}
}