There is a note that exactly fits you.
Use the @PostConstruct
annotation to define a method that runs so that ManagedBean
is built (according to the life cycle of its Bean
), that is, when the first EL
that references Bean
is found.
For example:
@ViewScoped
// ou
@RequestScoped
@Named
public class MeuBean {
@PostConstruct
public void inicializar() {
// Sua logica de inicializacao
}
}
There is also @PreDestroy
, similar to @PostConstruct
is called when a Bean
will be destroyed. The call varies in relation to the scope of your Bean
(the call depends on the life cycle). If you use a Bean
scope of View
there is a bug in most implementations that do not call this method the life cycle correctly.
This question predestroy-on-viewscoped addresses this behavior.
Because your Bean
is session, @PostConstruct
is only called once, regardless of how many times it is accessed on your page.
We know that the application server manages the Beans
lifecycle. Soon it will create and destroy your session bean. It will create at first reference to it and will destroy when the session is invalid, saving it in the session in the mean time.
I have two suggestions to solve the problem, which would be:
Replace the session Bean with a @ViewScoped
or @RequestScoped
, and "cache" the result of the processing it does or uses in the session. Using @PostConstruct
to print what you need on the console. This is valid if your% session% is no longer needed after this replacement.
Because of memory expense, it is even more advantageous than% session% to save only the result and not the entire Bean. But in terms of organization and OO, the Session Bean will do better because there will be a "context" around the data, all logic in relation to that data will be centered in one place. In case, the choice will depend a lot on how your organization is.
Create a Bean Bean
or Bean
and inject your session Bean to use it in @ViewScoped
. In terms of code it would look something like this:
@RequestScoped
@Named
public class MeuBeanDeImpressao {
// Injeto o Bean de sessão
@ManagedProperty("#{beanTeste}")
// ou
@Inject
BeanTeste beanTeste;
@PostConstruct
public void inicializa() {
beanTeste.imprimirNome();
}
}
This case is only beneficial if you still need the Session Bean, but you can use a Bean of @RequestScoped
or @PostConstruct
on your page (having use for other things, otherwise it might generate unnecessary memory expense). @RequestScoped
works best because there is no life cycle bug, it will be destroyed after use.