0

我是 EJB 新手并尝试为 EJB 有状态 bean 编写实现,但是当我尝试执行事务时,它像无状态 bean 一样返回

package beanpackage;

import javax.ejb.Stateful;
//import javax.ejb.Stateless;

/**
 * Session Bean implementation class bankbean
 */
@Stateful
public class bankbean implements bankbeanRemote, bankbeanLocal {
    /**
     * Default constructor. 
     */
    static int accountbalance;
    public bankbean() {
        accountbalance=10;
    }
    public int accountbalancecheck()
    {
        return accountbalance;
    }
    public int accountwithdraw(int amount)
    {
    return (accountbalance-amount);
    }
    public int accountdeposit(int amount)
    {
        return (accountbalance+amount);
    }
}




import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import beanpackage.bankbeanRemote;


public class appclient {
public static void main(String args[]) throws NamingException
    {
        Context c = appclient.getIntitialContext();
        bankbeanRemote bbr = (bankbeanRemote)c.lookup("bankbean/remote");
        int s = bbr.accountbalancecheck();
        System.out.print(s+"  this is first ejb output");
        s=bbr.accountwithdraw(1);
        System.out.print(s+"  this is first ejb output");
        s=bbr.accountwithdraw(1);
        System.out.print(s+"  this is first ejb output");
    }
public static Context getIntitialContext() throws NamingException
    {
        Properties prop = new Properties();
         prop.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
        prop.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
        prop.setProperty("java.naming.provider.url", "127.0.0.1:1099");
        return new InitialContext(prop);
    }
}

输出是:

10  this is first ejb output
9  this is first ejb output
9  this is first ejb output 

我无法理解。它应该返回 10 9 然后 8..但返回 10 9 9..请帮助

4

2 回答 2

3

你忘记了 decrement/increment accountbalance。我认为这是你打算做的:

public int accountwithdraw(int amount)
{
    accountbalance = accountbalance-amount;
    return accountbalance;
}

public int accountdeposit(int amount)
{
    accountbalance = accountbalance-amount;
    return accountbalance;
}

ps - 为什么您在 ejb 定义中使用注释而不是用于查找 ( @EJB) 的任何特殊原因?将更容易和更便携的 IMO。

于 2013-03-09T01:32:19.910 回答
1

在 fvu 答案之上,您不应该设为accountbalance静态,否则该值将由 bean 的所有实例共享。

像这样声明它:

int accountbalance;
于 2013-03-09T01:33:46.330 回答