]> git.argeo.org Git - gpl/argeo-slc.git/blob - SpringArg.java
cd85f89c7373b5efcd7220b8d4a34b30efcd9eed
[gpl/argeo-slc.git] / SpringArg.java
1 package org.argeo.slc.ant.spring;
2
3 import java.util.List;
4 import java.util.Vector;
5
6 import org.apache.tools.ant.types.DataType;
7 import org.argeo.slc.ant.SlcAntException;
8 import org.argeo.slc.ant.SlcProjectHelper;
9 import org.argeo.slc.core.SlcException;
10 import org.springframework.beans.BeanWrapper;
11 import org.springframework.beans.BeanWrapperImpl;
12 import org.springframework.beans.factory.InitializingBean;
13 import org.springframework.context.ApplicationContext;
14
15 /** Abstract Ant type wrapping a Spring bean. */
16 public class SpringArg<T> extends DataType {
17 private List<OverrideArg> overrides = new Vector<OverrideArg>();
18
19 private String bean;
20
21 // cache bean instance to avoid reading it twice if it is a prototype
22 private T beanInstance = null;
23
24 /** The <u>name</u> of the underlying bean, as set through the attribute. */
25 public String getBean() {
26 return bean;
27 }
28
29 /** Setter for the bean name. */
30 public void setBean(String bean) {
31 this.bean = bean;
32 }
33
34 /**
35 * Retrieve the instance of the bean, and sets the overriden properties.
36 * <b>The value is cached.</b>
37 */
38 public T getBeanInstance() {
39 if (beanInstance == null) {
40 beanInstance = (T) getContext().getBean(bean);
41
42 setOverridenProperties(beanInstance);
43
44 // FIXME: why are we doing this? Could not find any object using it
45 if (beanInstance instanceof InitializingBean) {
46 try {
47 ((InitializingBean) beanInstance).afterPropertiesSet();
48 } catch (Exception e) {
49 throw new SlcException("Could not initialize bean", e);
50 }
51 }
52 }
53 return beanInstance;
54 }
55
56 protected void setOverridenProperties(Object obj) {
57 BeanWrapper wrapper = new BeanWrapperImpl(obj);
58 for (OverrideArg override : overrides) {
59 if (override.getName() == null) {
60 throw new SlcAntException(
61 "The name of the property to override has to be set.");
62 }
63
64 // LogFactory.getLog(getClass()).debug(
65 // "Prop " + override.getName());
66 wrapper.setPropertyValue(override.getName(), override.getObject());
67 }
68
69 }
70
71 /** Creates an override subtag. */
72 public OverrideArg createOverride() {
73 OverrideArg propertyArg = new OverrideArg();
74 overrides.add(propertyArg);
75 return propertyArg;
76 }
77
78 /** The related Spring application context. */
79 protected ApplicationContext getContext() {
80 return (ApplicationContext) getProject().getReference(
81 SlcProjectHelper.REF_ROOT_CONTEXT);
82 }
83
84 }