use*_*984 5 java java-ee cdi java-ee-6 ejb-3.1
我是这里的新手,也是CDI世界的新手,我在工作中得到的第一项任务就是找到一种控制CDI上传的方法.
我们同时使用EJB 3.1和CDI 1.0,因为它们是由不同的容器控制的,我们可以控制何时和以何种顺序EJB管Bean将达到使用@Startup和@Singleton标注.
但是@Inject我在我的类中声明的CDI bean因为CDI容器尚未启动而变为空.
我已经尝试了好几天来寻找解决方案,而我在这里找到的解决方案没有用(仍然是空的).
我们正在使用Java EE 6并在WebSphere Application Server 8上运行该应用程序.
请问,如果你能帮我找到一种方法来控制内部和不管EJB的CDI上传?
这是一个示例代码:
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@Singleton
@Startup
public class BaseStartupLoader{
/**
* Default constructor.
*/
@Inject @MyStartup
BaseStartUp myStartup;
private static Logger m_logger = LoggerFactory.getLogger(BaseStartupLoader.class);
public BaseStartupLoader() {
}
@PostConstruct
public void init(){
String applicationName = null;
try {
applicationName = myStartup.getClass().getName();
myStartup.load();
} catch (IllegalAccessException e) {
m_logger.error("Faild to load data into preload system. "+e);
} catch (InstantiationException e) {
m_logger.error("Faild to load data into preload system. "+e);
} catch (ClassNotFoundException e) {
m_logger.error("Faild to load data into preload system - Class "+ applicationName + "Not found. "+e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是BaseStartup接口:
public interface BaseStartUp {
public void load() throws IllegalAccessException, InstantiationException, ClassNotFoundException;
}
Run Code Online (Sandbox Code Playgroud)
资格赛和实施:
@Retention(RetentionPolicy.RUNTIME)
@Target ({ElementType.PARAMETER, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Qualifier
@Dependent
public @interface MyStartup {
}
@MyStartup
public class MyStartUpLoader implements BaseStartUp {
@Inject
SomeConfigLoader config;
@Override
public void load() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
conifg.init();
}
}
Run Code Online (Sandbox Code Playgroud)
经过大量研究后,我找到了IBM人员的一些帮助,因为我们正在使用WebSphere Application Server,我可以添加一个名为的JVM属性:
"com.ibm.ws.cdi.immediate.ejb.start"= true
在管理控制台中的WAS中,他将确保一旦我在@Startup bean中获得EJB @PostConstruct方法,我创建的CDI容器就已经启动并且已经注入.
有用!!
以下是IBM站点中问题和解决方案的链接:
http://www-01.ibm.com/support/docview.wss?uid=swg1PM62774
也许需要仔细检查 CDI 是否确实在应用程序需要的所有位置启用。尝试添加此代码作为BaseStartupLoader实验:
@Singleton
@Startup
public class BaseStartupLoader {
@Inject @MyStartup
BaseStartUp myStartup;
@Inject
private InjectionTest test;
public static class InjectionTest {}
}
Run Code Online (Sandbox Code Playgroud)
如果test变量在 中出现 null @PostConstruct,则声明的 jar 中可能未启用 CDI BaseStartupLoader。
例如,如果BaseStartupLoader在名为 的 jar 中声明orange.jar并MyStartUpLoader在名为 的 jar 中声明yellow.jar,则这两个文件必须存在:
orange.jar!/META-INF/beans.xmlyellow.jar!/META-INF/beans.xml如果通过 a 在两个 jar 中正确启用了 CDI META-INF/beans.xml,则这是容器中的错误。在调用之前,所有@Inject要点都必须完成(对于启用 CDI 的 jar) 。@PostConstruct无论是否@Startup使用并且其中一个 Bean 恰好是 EJB,情况都是如此。