日期:2014-05-19  浏览次数:20675 次

手动new的对象,是否可以通过@EJB注入属性
各位达人,请问手动创建的对象,是否可以通过@EJB注解来注入对象。。

例如
class Demo{
@EJB
private MyClass myCl;
private String param

Demo(String param){
this.param = param
}
}

如果在代码使用new来创建,而不是由EJB框架来创建,那么能否自动注入MyClass对象。

Demo demo = new Demo("p");

//myCl.toString();

谢谢!

------解决方案--------------------
Java code

package sh.pl;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import javax.ejb.EJB;

public class TestEJBContainer {

    public static void injectEJB(Object obj) throws IllegalArgumentException, IllegalAccessException, InstantiationException {
        if (obj == null) return;
        Field fields[] = obj.getClass().getDeclaredFields();
        for (Field f : fields) {
            Annotation a = f.getAnnotation(EJB.class);
            if (a != null) {
                //注入
                f.setAccessible(true);
                f.set(obj, f.getType().newInstance());
                f.setAccessible(false);
            }
        }
        
    }
    
    public static void main(String[] args) {
        Demo demo = new Demo("p");
        try {
            injectEJB(demo);
            System.out.println(demo.getMyCl().toString());
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
    }
}

------解决方案--------------------
不可以。
从spring容器中拿出的对象才可以。