有状态的bean表现得像一个无状态的bean

时间:2013-03-09 01:28:03

标签: java jboss ejb stateless-session-bean stateful-session-bean

我是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 ..请帮助

2 个答案:

答案 0 :(得分:3)

你忘记减少/增加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。

答案 1 :(得分:1)

除了fvu回答之外,你不应该使accountbalance为静态,否则这个值将由bean的所有实例共享。

只需声明如下:

int accountbalance;