01: /*
02: * JFox - The most lightweight Java EE Application Server!
03: * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
04: *
05: * JFox is licenced and re-distributable under GNU LGPL.
06: */
07: package org.jfox.entity.dependent;
08:
09: import java.lang.reflect.Field;
10: import javax.persistence.EntityManagerFactory;
11: import javax.persistence.PersistenceUnit;
12:
13: import org.jfox.ejb3.EJBBucket;
14: import org.jfox.entity.EntityManagerFactoryBuilderImpl;
15: import org.jfox.framework.dependent.Dependence;
16: import org.jfox.framework.dependent.InjectionException;
17:
18: /**
19: * 注入 @PersistenceUnit
20: *
21: * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
22: */
23: public class FieldPersistenceUnitDependence implements Dependence {
24:
25: private EJBBucket bucket;
26: private Field field;
27: private PersistenceUnit pu;
28:
29: public FieldPersistenceUnitDependence(EJBBucket bucket,
30: Field field, PersistenceUnit pu) {
31: this .bucket = bucket;
32: this .field = field;
33: this .pu = pu;
34: }
35:
36: public void inject(Object instance) throws InjectionException {
37: EntityManagerFactory emf;
38: String unitName = pu.unitName();
39: if (unitName.trim().length() == 0) {
40: emf = EntityManagerFactoryBuilderImpl
41: .getDefaultEntityManagerFactory();
42: } else {
43: emf = EntityManagerFactoryBuilderImpl
44: .getEntityManagerFactoryByName(unitName);
45: }
46:
47: if (emf == null) {
48: throw new InjectionException("Failed to inject field "
49: + field.getName() + " of @PersistenceContext "
50: + bucket.getEJBName()
51: + ", because could not find PersistenceUnit: "
52: + unitName);
53: }
54: // 使用 field å??射注入
55: try {
56: field.setAccessible(true);
57: field.set(instance, emf);
58: } catch (Exception e) {
59: throw new InjectionException("Failed to inject field "
60: + field.getName() + " of @PersistenceContext "
61: + bucket.getEJBName(), e);
62: }
63: }
64:
65: public static void main(String[] args) {
66:
67: }
68: }
|