2

What is the difference between

public UserBean() {
        // create the session state
        state = new BigInteger(64, new SecureRandom()).toString(32);

}

and

public UserBean() {
        init();
}

@PostConstruct
    public void init() {
        // create the session state
        state = new BigInteger(64, new SecureRandom()).toString(32);            
    }

where state is one of the many attributes of the class.

Cœur
  • 37,241
  • 25
  • 195
  • 267
overflow
  • 85
  • 1
  • 1
  • 8
  • State will be instantiated when the UserBean is instantiated. In other case, UserBean will be instantiated and then the state will get instantiated. – Yati Sawhney Feb 22 '18 at 14:15
  • first one exact after building of new instance initialize ``state``, second one after initialization call method ``init``(which initialize ``state``) and again call ``init`` method when fired event post construct. ``@PostConstruct`` fired when all context for bean initialized. – reconnect Feb 22 '18 at 14:17
  • Calling an overridable method in a constructor should not be done (make it final). Here it also is not needed because of @PostConstruct. The link of the prior comment says the rest. – Joop Eggen Feb 22 '18 at 14:19

1 Answers1

1

You misunderstand the @PostConstruct annotation.
A method annotated with should be invoked by the container after dependency injection was performed. It has not to be invoked by your applicative code.

So of course using @PostConstruct without container (EJB, Spring, Guice...) makes no sense.

The @PostConstruct doc states :

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

To summarize :

  • the container creates the bean by invoking the constructor
  • the container sets the bean dependencies
  • the @PostConstruct method is invoked

Note that between the steps 1, 2 and 3, the container may perform other tasks for other beans but you should not worry about that as the javadoc also states that @PostConstruct method MUST be invoked before the class is put into service.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I am working with jsf2 and using tomcat. So does tomcat takes care of @postConstruct? – overflow Feb 24 '18 at 23:19
  • Tomcat alone, no. It is not a component container. It is a servlet container. If you add Spring as component container in your app, Spring will take care of it. – davidxxx Feb 25 '18 at 22:51
  • But it is in jsf 2.2 code. Are you saying there is nothing in jsf to take care of it? i thought jsf was an alternative to spring. – overflow Feb 25 '18 at 23:07
  • About managed beans of JSF2, no idea. On the internet, we could read that yes. So give it a go. – davidxxx Feb 25 '18 at 23:13