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(); } }