2011-05-18 83 views
0

看一看下面的代码:EJB嵌入式容器 - 依赖注入不起作用?

@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实例,但是它是等于空。所有类都是一个项目的一部分(放置在分离的文件中)。我犯了什么错误?谢谢你的建议。

+0

看起来应该可以工作。你在使用什么应用程序服务器?仅供参考,您应该使用EJBContainer.getContext()而不是新的InitialContext() – 2011-05-18 20:34:17

+0

我正在使用Glassfish 3.1。在第一个版本中我有EJBContainer.getContext(),但它也没有工作。 – Rafal 2011-05-18 20:41:34

+0

啊,是的,当然。您正在使用无接口视图。查找返回一个代理,它必然是NIV的一个子类。由于该方法是私有的,因此您直接在代理上调用方法,该方法没有注入。 – 2011-05-18 23:28:34

回答

0

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