EJB嵌入式容器 - 依赖注入不起作用?

时间:2011-05-18 17:28:51

标签: java java-ee dependency-injection ejb ioc-container

查看以下代码:

@Local
public interface MyService {

    void printMessage();
}

@Stateless
public class MyServiceImpl implements MyService {

    @Override
    public void printMessage() {
        System.out.println("Hello from MyService.");
    }
}

@Stateless
@Named
public class Application {

    @EJB
    public MyService sampleService;

    private static Application getApplication() throws NamingException {
        Properties properties = new Properties();
        properties.setProperty(EJBContainer.APP_NAME, "admin");
        EJBContainer.createEJBContainer(properties); //.getContext();
        Context context = new InitialContext();

        Application application = (Application) context.lookup("java:global/admin/classes/Application");
        return application;
    }

    public static void main(String[] args) throws NamingException {
        Application application = getApplication();
        application.start(args);
    }

    private void start(String[] args) {
        sampleService.printMessage();
    }
}

我希望在start()操作中可以使用simpletService实例,但它等于null。所有类都是一个项目的一部分(放在单独的文件中)。哪里弄错了?谢谢你的建议。

1 个答案:

答案 0 :(得分:0)

最后我找到了解决方案。当我将start()操作改为公开并且注入开始工作正常时。