Using @PostConstruct vs constructor initialization

I've been reading through an EJB 3 book. I've noticed that lots of the examples of stateful session beans use methods marked with @PostConstruct to do member variable initialization instead of just initializing them in the constructor. There must be a reason for this, right?
Can anybody explain the purpose for this?

Hi,
The reason is that in EJB dependency injection (access to resources, other EJBs etc) is done by the container after the constructor is called and before any @POSTCONSTRUCT annotated method is called. Therefor, at the time that a @POSTCONSTRUCT annotated method is executed, the EJB has all dependecies initialized.
HTH Robert

Similar Messages

  • Can we use an overloaded constructor of a Java Bean with Session Tracking

    Hi Friends,
    If any one can solve my query.... It would be helpful.
    Query:
    I have a Java Bean with an overloaded constructor in it. I want to use the overloaded constructor in my JSP.
    1. One way of doing that is to use it directly in the "Scriptlets" (<% %>). But then I am not sure of the way to do session tracking. I think I can use the implicit objects like "session", "request" etc. but not sure of the approach or of the implementation method.
    2. Another way is through the directive <jsp: useBean>. But I cannot call an overloaded constructor with <jsp: useBean>. The only alternative way is to use the directive <jsp: useBean> where I have to write getter and setter methods in the Java Bean and use the <jsp: setProperty> and <jsp: getProperty> standard actions. Then with this approach I cannot use the overloaded constructor.
    Can any one suggest me the best approach to solve this problem ?
    Thanks and Regards,
    Gaive.

    My first reaction is that you can refactor your overloaded constructor into an init(arguments...) method. Instead of overloaded constructor, you can call that init method. This is the ideal solution if possible.
    As to the two choices you listed:
    1. This is OK, I believe. You can use scriplet to define the bean and put it into session scope of the pageContext. I am not sure exactly what you meant by session tracking; whatever you meant, it should be doable using HttpSessionAttributeListener and/or HttpSessionBindingListener.
    2. Agreed. There is no way that <jsp:useBean> can call a constructor that has non-empty arguments.
    Please tell me how it works for you.

  • Use method in constructor?

    Is it possible to call a method in a constructor if that method belongs to the same class? Will there be problems calling the method since the object hasn't been completely created yet?
    Example code:
    Class Foo
      // constructor
    public Foo()
       method bar();
    public void bar()
    }In my class, I'd like to initialise some attributes in the constructor. After object creation, that initialisation (which includes some ordening) should also be available as a public method, to re-order my attributes if necessary. I'd like to avoid using double code for the ordering (both in the constructor and in the method).

    Is it possible to call a method in a constructor if
    that method belongs to the same class?
    Yes, but it's often not recommended for the reason you have discovered:
    Will there be problems calling the method since the object hasn't
    been completely created yet?
    This depends on what the method does and at which point you call it. The object has been fully created, it's just not properly initialized. If you call the method after you've set all instance variables to their initial values there should be no problem.
    But you should make that method final, private, or static so that it won't be possible to override it from subclasses. If someone writes a subclass that overrides that method, the method will be called before the subclass instance has had any chance to initialize itself which is a likely source of bugs.

  • Using classname in constructor

    When running the following on the compiler I get an error:
    class Employee{
    public Employee(){
    public Employee(String name, String id, String department, double salary){
    Employee();
         this._name=name;
         this._id=id;
         this._department=department;
         this._salary=salary;
    When I change Employee(); to this(); it works. I'm just wondering if the first version is supposed to technically work?

    It makes no sense to call "Employee();" in your
    extended constructor. You use the constructor
    Employee() with the this-operator in your extended
    constructor as you already explained correctly.
    Employee() constructor is default so you don't have to
    code it again as you did.
    Although Employee() does not seem to do anything it is
    needed to allocate memory for the object to be
    instantiated from the relevant class.No quite. If you invoke Employee(name, id, department, salary), the no-arg constructor Employee() will not[i/] be called unless you invoke it explicitly. The constructor does not allocate memory for the object being instantiated. That is done by the VM before the constructor is even called.
    The only implicit constructor call is an implicit super() if the first line of the running constructor is not super() or this().
    However, it is true that you don't need to invoke this(). You can if you want to centralize certain initializations, but the language doesn't require it, and there is no implicit this() call from other constructors.

  • Using Shared Variables and Initialize Front Panel Binding (to PSP)

    Hi,
    I use LV DSC RT 8.2.1
    I have a Vacuum System That includes signals from - Pumps failure, Valves status, Vacuum gauge, start Pump ...
    Each signal is read by a FieldPoint. 
    All the relevant FieldPoint Channels are read by the Server (a computer in the Ethernet Network) and published to the network in the form of Shared Variables.
    I have a client VI that is reading the Shared Variables published by the Server using Front Panel Binding.
    Problem : 
    Some of the Bindings are in the mode 'Write &Read' and that causes some initialization problems.
    For example - Valve #1 is Open, and then a User start running the Client VI, (the Valve #1 Status mode is 'Write & Read")
                           if in the VI the status of Valve #1 is closed (before running it) then the Valve status is changing to Closed.
    I want the Client VI to first read the Physical status of the instrument and then to change the Value if the User changes it.
    But that's seems to be a problem when using Front Panel Binding... (is it?)
    I know I can Deploy a lvlib in the Client Side and Item Bind to the Shared Variables or Use DataSocket.
    (Is DataSocket is a Reliable method when connecting to Shared Variables? What are the disadvantages when using DataSocket?) 
    What is recommended by those of you that are experienced or by NI ?
    Sincerely Yours,
    Amitai Abramson.

    Amitai Abramson,
    Hello and thanks for using the NI Forums.
    I'm glad that you've read the Using the LabVIEW Shared Variable Tutorial on our website. Check out these other resources:
    Network Variable Technical Overview
    Troubleshooting Network-Published Shared Variables
    Why Do I See Unexpected Value Change Events for Shared Variables Using LabVIEW DSC?
    All You Need to Know About Shared Variables
    Creating a Value Change Event for Shared Variables
    Alternative Method for Using Shared Variables Between Systems in LabVIEW 8.x
    What Is The Difference Between Using Shared Variables And DataSocket VIs To Access OPC Tags?
    The issue that you are seeing by having "Write & Read" bound items on both the server and client side is essentially a race condition, you don't know which one is being read/written at what time. To resolve this issue I would take a look at some of the documents below.
    Using a Local, Global, or Shared Variable in Parallel Loops Can Cause Race Conditions
    Using Local and Global Variables Carefully
    Tutorial: Local Variable, Global Variable, and Race Conditions
    Locking a Shared Resource or Variable in LabVIEW Using Semaphores
    You mentioned not wanting to have two sets of shared variables (one on each side), but this is a great method to resovle this issue, that, or you can develope some sort of hand shaking to prevent these race conditions.
    I would suggest that in the future when using these forums you try to ask only one question per thread and make it more concise. It's hard to tackle multiple questions and such broad questions as "I want to know all the ways that I can connect to Shared Variables, and I want to know the advantages and disadvantages." I suggest this because we want you to get your questions answered and more concise questions will result in quicker and better answers. 
    Message Edited by Ben S on 10-01-2009 06:05 PM
    Ben Sisney
    FlexRIO V&V Engineer
    National Instruments

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

  • Why could the "this" be used in the constructor of a class?

    We often see this kind of code below:
    public class myClass1 {
    private List list;
    public myClass1(String aStr){
    this.list = new List(12, false); // The "this" is what confuses me.
    The code above seems nature. But the question is that the "this" means "the instance of the current class", and we say that the instance of a class initiates after the constructor of the class is invoked.
    How could it happen that the JVM knows "this" before it class is initiated ?

    I have found that this convention very helpful, especially when you remember that you're using the new operator:class MyClass
      int x;
      int y;
      public MyClass ( int newx, newy )
        x = newx;
        y = newy;
      void setPos ( int newx, newy )
        x = newx;
        y = newy;
    }This avoids the unnecessary use of this
    Doug

  • How to use session variables in initialization blocks

    Hello,
    I want to use a session variable in a initialization block. Here is what I was doing to see this working
    I created a init block called name_parameter and associated with a variable target named name_parameter_v. The init string for this block is "select 'Hello' from dual".
    i created another init block name_parameter2 and associated with a variable target named name_parameter2_v. The init string is "select :name_parameter_v from dual".
    I have selected name_parameter in the edit execution precedence for name_parameter2.
    The result set is empty. Could you please explain why I am not able to see Hello when i test name_parameter2.
    Thanks.

    to obtain the value contained in a session variable this is the syntax.
    select 'VALUEOF(NQ_SESSION.VARIABLE_NAME)' from dual
    mind the single quotes, they are necessary

  • Help on using NewObject with constructors!

    Hi,All:
    I want to create an object in a native method. The object is an instance of an inner class. The inner class has two constructors: one default and one with two arguments. There is no problem if I use NewObject with the default construtor. But if I use NewObject with the constructor taking two int arguments. The JVM crashes.
    Can anybody give me some idea what the problem is?
    Thanks!
    Tao
    Here is the native method, the inner class and error message:
    JNIEXPORT jobject JNICALL Java_Prompt_createtp(JNIEnv *env, jobject obj)
         jobject test_ttt= 0;
         jclass cls2;
         jmethodID cid;     
         jint a,b;
         jfieldID fid;
         a = 10; b = 20;
         cls2 = (*env)->FindClass(env,"LPrompt$tp;");          
         cid = (*env)->GetMethodID(env,cls2,"<init>","(LPrompt;II)V");     
    test_ttt = (*env)->NewObject(env,cls2,cid,a,b);
    // However, the following codes using default constructor works well
    //cid = (*env)->GetMethodID(env,cls2,"<init>","(LPrompt;)V");     
    //test_ttt = (*env)->NewObject(env,cls2,cid);
    (*env)->DeleteLocalRef(env,cls2);
         return test_ttt;
    // here is the inner class     
    class tp{
    int a;
    int b;
    tp(){
    a = 100;
    b = 0;
    tp(int x,int y){
    a = x; b = y;
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # Internal Error (53484152454432554E54494D450E43505001A3), pid=276, tid=640
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode)
    # An error report file with more information is saved as hs_err_pid276.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    #

    You are getting the constructor id on a signature that looks like:
    Prompt(Prompt p, int n1, int n2)I guess that your constructor signature is:
    Prompt(int n1, int n2)So it should ne:
    cid = (*env)->GetMethodID(env,cls2,"<init>","(II)V");Next time please paste your code between code tags exactly like this:
    &#91;code&#93;
    your code
    &#91;/code&#93;
    You may read the [url http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips for more information.
    Regards

  • Sample Program Using Method And Constructor

    Pls. help me... pls. post just a simple running program... that uses a method and constructor getter and setter..... my program doesn't do anything
    public class Attraction{
         public int minutes;
         public Attraction(){
              minutes = 75;}
         public Attraction(int m){
              minutes = m;}
         public int getMinutes(){
              System.out.println("Reading an attraction's minutes...");
              return minutes;}
         public void setMinutes(int m){
              System.out.println("Writing an attraction's minutes...");
              minutes = 7;}
    }

    public class Attraction{
         public int minutes;
         public Attraction(){
              minutes = 75;}
         public Attraction(int m){
              minutes = m;}
         public int getMinutes(){
    System.out.println("Reading an attraction's
    s minutes...");
              return minutes;}
         public void setMinutes(int m){
    System.out.println("Writing an attraction's
    s minutes...");
              minutes = 7;}
    //new code added
    public static void main(String arg[]){
    Attraction att=new Attraction();
    att.setMinutes(14);
    att.getMinutes();
    }

  • How to use this color constructor ?

    Color(int rgb)
    Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.when i pass in 56, then i get blue. when i pass in 100 or 300, i get black. what is the magic to use this constructor ?
    can some1 tell me how to get green or red ?
    thanks

    As the docs say, the bits 16-23 should contain the red component, the bits 8-15 should contain the green component and the bits 0-7 should contain the blue component. Since we're dealing with bits it's easier to do the work in hex, namely 0xFF0000 = 16711680(base 10) is red, 0xFF00 = 65280(base 10) is green, 0xFFFF00 = 16776960(base 10) is yellow and so on.

  • Use of protected constructors.

    Hi all,
    I understand the uses of making a constructor private or package-private, I was wondering what could be the possible uses of making a constrcutor protected.
    From what I understand a constructor could be made protected for immutable objects with static factory methods where the subclass in the other package is TRUSTED not to voilate the superclass's invariants but is only expected to better the implementation or add more attributes.
    Another reason what I can think of is a Singleton, where again the subclasss in the other package is TRUSTED not violate the singleton semantics but add additional services/behaviour.
    Am I right in what I am thinking? Are there more benefits?
    Thank you very much for your time,
    Amnesiac.

    If a class is designed for subclassing then it may have protected constructors different from its public constructors to allow the subclasses a bit more control about initializing thier superclass. In these cases the public constructors often call the protected ones with some default values that make sense for the base class.
    Not a common occurrence though.
    matfud

  • Using dashboard prompts to initialize session variables

    hi everyone,
    I want to know if it's possible to have a dashboard prompt that is only used to change session variables. This prompt would stay in a tab without any report.
    Can this be done?

    when the user changes the variables in the promptI guess its value not the variables ....am i right?
    the variables seem to work just in the tab where the prompt is, although the prompt is set to be valid in the dashboard.1 ) Request/Presentation variable scope is in Dashboard or page
    2) As i shown in screen shot in a Dashboard Demo have two pages req variable and multi select when i change the value in prompt it was changing the value in qty variable means initializing the session variable value
    The screen shot dat i gave is what are you looking or some thing else??
    thanks,
    saichand.v

  • Use Daqmx Trigger to initialize software

    Hello,
    I am using an NI PCIe-6537B to run an SMB-2163 High-Speed DIO Accessory.  I have a high speed camera sending out triggers whenever a frame is captured.  Each time the trigger is received into PFI4, a digital output (DIO#) sends out a waveform. 
    I would like to know if it is possible to read that trigger so that I can use it to trigger other things in the software "simultaneously."
    I have attempted to simply read PFI4 as a digital input (Digital Bool 1 Line1 Point) while also using it as the external trigger.  It worked for a while but after I left the project it now seems to only randomly read when the trigger is sent.  Not knowing what changed since it last worked, am I doing this correctly or is there a better way to do this?  Perhaps using the Daqmx events.
    Any help is greatly appreciated!
    Thanks,
    Mike S.
    CLAD
     

    Hey Mike,
    A couple of things here.  Firstly, for the Change Detection timing type, you will not need to use the event structure in your program.  This is implemented in hardware, with samples being latched when the configured lines show the change.  Basically, every time the configured line changes, the DAQmx read will return the values of all lines configured for your channel.
    Also, you will not be able to use PFI4 as the source for change detection.  You will have to specify a data line (ports 0-3) for use with the change detection timing type.  Here's some documentation I could find about using this:
    http://www.ni.com/white-paper/4102/en/
    http://digital.ni.com/public.nsf/allkb/4B9452520950566A86256F31006C9AEF
     

  • Using super class constructor in subclass constructor

    Hi all. How can I use Person() in my Client()?
    something like this:
    public class Client extends Person{
          private float balance;
          Client(String firstName,String midleName,String lastName,Contacts contacts,Adress adress,float balance){
               this= Person(firstName,midleName,lastName,contacts,adress);
               this.balance=balance;
          }

    public class Client extends Person{
      private float balance; // float?!? Are you sure.... ?
      Client(String firstName,String midleName,String lastName,Contacts contacts,Adress adress,float balance){
        super(firstName,midleName,lastName,contacts,adress);
        this.balance=balance;
    }

Maybe you are looking for

  • Updation of Custom Fields in AFRU table Using Customerexit

    Hi all, I added two fields in CO11n Tcode using SCREEN EXIT - CONFPP07 and iam trying to update these two fields in AFRU table using CONFPP05.  But iam unable to update these two field . see this code in CONFPP05   LOOP AT afrud_tab.     afrud_tab-zz

  • ITunes 10.7 crashing

    My iTunes is crashing every time I try to open it. I have thousands of dollars of music and movies in there. PLEASE HELP!!!! Process:         iTunes [1033] Path:            /Applications/iTunes.app/Contents/MacOS/iTunes Identifier:      com.apple.iTu

  • Possible Deleted Folder Problem with Iphoto 09

    Ok, I've run into a kind os odd problem. I've been able to tell that all of my pics are still on my hard drive in the iphoto library, however iphoto won't display any images. After doing a little digging it seems that my "data" folder is missing, and

  • Summary list of counts

    I'm trying to display a summary count of distinct values in a table based on their group category in a lookup table. The query for the summary page looks like this... SELECT rfs_category, lookup_value_desc, COUNT (*) the_count FROM seeker_rfs LEFT OU

  • What does the error message "Opening file in iCloud(state=5) mean?

    I have been ushing iCloud to backup my data for Ascendo DataVault for my iPhone 5 (iOS 7.0.4) and original iPad (iOS 5.1.1) very successfully for some time.  Both devices are synchronized with my PC using Wi-Fi.  The DataVault data on my PC is also s