Spring4.0支持Groovy配置

介绍

前一段时间观注了一下Spring4.0的一些特性,其中就有对Groovy配置的支持。由于暂时还没有非常深入的研究,所以举个小例子来说明一下如何支持Groovy配置。


package shuai.study.spring.bean;

public class Gasoline {
	private int capacity = 0;

	public Gasoline(int capacity) {
		this.capacity = capacity;
	}

	public int getCapacity() {
		return this.capacity;
	}
}

package shuai.study.spring.bean;

public class Car {
	private String name = null;
	private Gasoline gasoline = null;

	public Car(Gasoline gasoline) {
		this.gasoline = gasoline;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void run() {
		int capacity = gasoline.getCapacity();

		if (gasoline.getCapacity() > 100) {
			System.out.println("Gasoline capacity is " + capacity + ", " + this.name + " could start to run.");
		} else {
			System.out.println("Gasoline capacity is " + capacity + ", " + this.name + " is not enough to run.");
		}
	}
}


car-config.groovy configuration file:

import shuai.study.spring.bean.Car
import shuai.study.spring.bean.Gasoline

beans {
	/*
		In class Car, we know that we defined variable gasoline as parameter of Car's constructor.
		Here we point out this variable's class(i.e. Gasoline), meanwhile set parameter's value of
		(Gasoline's) constructor
	*/	
    gasoline(Gasoline, 80)

	/*
		Define bean(i.e. car), and point out this bean's class(i.e. Car), meanwhile inject variable 
		gasoline to it. naturally we inject its variable(i.e. name) as well.  
	*/
    car(Car, gasoline) {
        name = "Benz"
    }
}

package shuai.study.spring.bean;

import org.springframework.context.support.GenericGroovyApplicationContext;

public class CarApp {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		GenericGroovyApplicationContext context = new GenericGroovyApplicationContext("classpath:spring/bean/car-config.groovy");

		Car car = (Car) context.getBean("car");
		car.run();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值