CDI SessionScoped with inheritance from an abstract class - jsf-2

I try to use the javax.enterprise.context.SessionScoped and javax.inject.Named
in my contoller that inherits from an abstractContoller (Referentiel.java)
#SessionScoped
#URLMapping(id = "account", pattern = "/page_comptes", viewId = "/referentiel/PgComptes.jsf")
#Named
public class AccountManagementBean extends Referentiel implements java.io.Serializable {
private static final long serialVersionUID = 5471453156487838630L;
//
}
and the Referentiel abstract class
public abstract class Referentiel {
#EJB
protected ReferentielDaoLocal ejbRef;
protected String filterChain;//useed to search in emetteurList
protected Gouvernorat selectedGouvernorat;
protected Commune selectedCommune;
protected Localite idLocalite;//used for edit emetteur
protected transient SessionLoader loader = new SessionLoader();
public Referentiel() {
}
protected abstract ReferentielDaoLocal getRefEJB();
//getters ans setters
}
I got this exception when deploying the application on Glassfish 4
SEVERE: Exception while loading the app : CDI deployment failure:WELD-001437 Normal scoped bean class org.ccf.sicav.bean.refentiel.Referentiel is not proxyable because the type is final or it contains a final method public final org.ccf.sicav.domain.Localite org.ccf.sicav.bean.refentiel.Referentiel.getIdLocalite() - Managed Bean [class org.ccf.sicav.bean.refentiel.AccountManagementBean] with qualifiers [#Default #Any #Named].
org.jboss.weld.exceptions.DeploymentException: WELD-001437 Normal scoped bean class org.ccf.sicav.bean.refentiel.Referentiel is not proxyable because the type is final or it contains a final method public final org.ccf.sicav.domain.Localite org.ccf.sicav.bean.refentiel.Referentiel.getIdLocalite() - Managed Bean [class org.ccf.sicav.bean.refentiel.AccountManagementBean] with qualifiers [#Default #Any #Named].
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:187)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:208)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:519)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:505)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:480)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:536)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:216)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:493)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001437 Normal scoped bean class org.ccf.sicav.bean.refentiel.Referentiel is not proxyable because the type is final or it contains a final method public final org.ccf.sicav.domain.Localite org.ccf.sicav.bean.refentiel.Referentiel.getIdLocalite() - Managed Bean [class org.ccf.sicav.bean.refentiel.AccountManagementBean] with qualifiers [#Default #Any #Named].
at org.jboss.weld.util.Proxies.getUnproxyableClassException(Proxies.java:232)
at org.jboss.weld.util.Proxies.getUnproxyableTypeException(Proxies.java:181)
at org.jboss.weld.util.Proxies.getUnproxyableTypesExceptionInt(Proxies.java:198)
at org.jboss.weld.util.Proxies.getUnproxyableTypesException(Proxies.java:171)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:185)
... 42 more

Related

Spring elasticsearch java.net.UnknownHostException

Trying to update a small experimental Spring Elasticsearch project to reflect changes in the 3.2.6 release reference guide.
As noted: TransportClient is deprecated as of Elasticsearch 7 and will be removed in 8. Trying to reconfig to High Level Rest Client.
But getting the following errors
Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticDatasource' defined in file [/Users/erichuang/Desktop/JE/00-Development/dev/lab/lab-elastic-search/lab-elastic-search/target/classes/com/elastic/labelasticsearch/config/ElasticDatasource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
com.elastic.labelasticsearch.LabElasticSearchApplication.main(LabElasticSearchApplication.java:15)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
... 24 common frames omitted
Caused by: java.net.UnknownHostException: localhost/<unresolved>: nodename nor servname provided, or not known
at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:932)
at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1505)
at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:851)
at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1495)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1354)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1288)
...
... 63 common frames omitted
Old setup (works)
ElasticSearchConfig
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class ElasticSearchConfig {
private static final String esHost = "localhost";
private static final int esPort = 9300;
#Bean
public Client client() throws UnknownHostException {
var transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(esHost), esPort));
return transportClient;
}
#Bean(name ={"elasticsearchOperations", "elasticsearchTemplate"})
public ElasticsearchOperations esTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(client());
}
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
New Setup
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class RestClientConfig extends AbstractElasticsearchConfiguration {
#Override
#Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9300")
.build();
return RestClients.create(clientConfiguration).rest();
}
}
What am I missing?
This is a bug resulting from as change in Java 14 in the java.net.InetSocketAddress.toString() method. This has been fixed in 4.0.RC2 (released yesterday).
Edit: I will backport this into the 3.2 branch as well
You will need to configure your bean using this way that allow to separate the host port and http protocol used:
#Configuration
#EnableElasticsearchRepositories(basePackages = "*")
public class ElasticsearchClientConfig {
#Value("${elasticsearch.host}")
private String host;
#Value("${elasticsearch.port}")
private int port;
#Value("${elasticsearch.protocol}")
private String protocol;
#Value("${elasticsearch.username}")
private String userName;
#Value("${elasticsearch.password}")
private String password;
#Bean(destroyMethod = "close")
public RestHighLevelClient restClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}

Spring data neo4j repositories not working since DATAGRAPH-939

I'm using:
Spring-data-neo4j 4.2.0-SNAPSHOT (tried with 4.2.0.RC1 too)
and since the DATAGRAPH-939 commit, I'm not able to work with repositories anymore.
#Repository
public interface MyEventRepository extends GraphRepository<Event> {}
The error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myEventRepository': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1148)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:735)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 41 common frames omitted
Here is an example of my failing test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SimpleTest.TestConfiguration.class })
public class SimpleTest {
#Configuration
#EnableNeo4jRepositories("com.nagra.ml.sp.cpm.core.repositories.test")
public static class TestConfiguration {
#Bean
public org.neo4j.ogm.config.Configuration configuration() {
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
config .driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
return config;
}
#Bean
public SessionFactory sessionFactory() {
return new SessionFactory(configuration(), "com.nagra.ml.sp.cpm.model");
}
#Bean
public Neo4jTransactionManager transactionManager() {
return new Neo4jTransactionManager(sessionFactory());
}
}
#Test
public void test() {
assertTrue(true);
}
}
According to documentation, the way of declaring repositories seems to be correct, am I doing something wrong ?
Thanks
I no longer have issues with repositories. I'm now using SDN 4.2.0.RELEASE with Spring boot 1.5.1 and I no longer extends GraphRepository as explained in SDN4.2.0 documentation.

Circular reference trying to configure custom permission evaluator in spring security

I'm trying to configure a custom permission evaluator but whenever the app starts up it's complaining of a circular reference.
The configuration code is:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
private static Logger logger = LogManager.getLogger(MethodSecurityConfig.class.getName());
#Autowired
DataSource dataSource;
#Autowired
Environment env;
#Autowired
AuthenticationManager auth;
public MethodSecurityConfig() {
logger.debug("Loading method security config.");
}
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return auth;
}
/**
* Override to set up the custom expression handler.
* #return The custom expression handler
*/
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return expressionHandler();
}
/**
* Defines a custom permission evaluator to evaluate the access permissions for Spring security.
* #return The default expression handler configured with a custom permission evaluator.
*/
#Bean
public DefaultMethodSecurityExpressionHandler expressionHandler(){
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setPermissionEvaluator(permissionEvaluator());
return handler;
}
/**
* Custom implementation of a permission evaluator
* #return An instance of {#link BasePermissionEvaluator}
*/
#Bean
public PermissionEvaluator permissionEvaluator() {
return new BasePermissionEvaluator();
}
}
When the app start up this exception occurs:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.setPermissionEvaluator(java.util.List); nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'permissionEvaluator': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[AutowiredAnnotationBeanPostProcessor.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) ~[AbstractBeanFactory$1.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[DefaultSingletonBeanRegistry.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) ~[AbstractBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) ~[AbstractBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368) ~[ConstructorResolver.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(A
What am I doing wrong here? I tried various things like adding the AuthenticationManager. Is there something else I need to override?
I had faced the same issue. In my case the reason was there was another security configuration class which has #EnableGlobalMethodSecurity annotation. Removing that annotation solved the issue.
The reason to have two security configuration classes is described here.
To my understanding this happens when Spring first processes the other configuration class, because of #EnableGlobalMethodSecurity permissionEvaluator and similar beans are registered that time and later when this configuration class is processed we got this error.
Also looks like this behaviour is arbitrary, depends on which configuration class is first processed based on classpath ordering.

Injecting a Bean Instance Returned by Factory class

I am working on a piece of code wherein I have a Spring Bean say B.java.
The constructor for this Bean depends upon 2 arguments.
Additionally this Spring Bean has another Spring Bean, say C.java injected to it.
I have a factory class say Factory.java that has a getInstance() Method that returns a new object of type B.java depending upon the passed in constructor parameters.
Now I want to inject the returned instance of class B in another class, say C.java which is a Spring Bean with all its properties instantiated i.e the reference to C.java as well.
Can somebody please help in creating context.xml files for this.
Following is a rough prototype of the class structures:
public class B{
private String arg1;
private String arg2;
private C c;
public void setC(C c){
this.c=c;
}
B(String arg1, String arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
}
................................
public class Factory{
private String arg1;
private String arg2;
public B getInstance(){
return new B(arg1, arg2);
}
}
...............................
public class C{
#Autowired
private B b;
#Autowired
private D d;
}
Thanks

Why can't I Init attribute in Managed Bean constructor?

I have a Managed Bean:
public class CategoriaManagedBean {
#EJB
private CategoriaBeanLocal categoriaBean;
private Categoria categoria;
private List<Categoria> menu;
}
In my constructor I try:
public CategoriaManagedBean() {
menu = categoriaBean.findByIdCategoriaPadre(0);
}
But I get a error "Cannot create the instance of the class", why can't I initialize the attribute in the constructor?
I fix the problem with:
#PostConstruct
public void init() {
menu = categoriaBean.findByIdCategoriaPadre(0);
}
But I want to know the reason and if I am doing well with #PostConstruct
Greetings.
Using #PostConstruct is the correct approach.
EJBs are injected after the constructor is invoked on a ManagedBean.
That's why there is a #PostConstruct annotation.
Here's the first line from the documentation:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

Resources