0

I can autowire Spring @Repository class in JSF Managed Bean, but cannot autowire @Service class, what is the problem?
LoginBean.java

@ManagedBean(name = "loginBean")
@ViewScoped
public class LoginBean implements Serializable
{
    private String username;
    private String password;

    @Autowired
    private AccountService accountService;

    public LoginBean()
    {
    }

    @PostConstruct
    public void init()
    {
        FacesContextUtils.getRequiredWebApplicationContext(FacesContext.getCurrentInstance()).getAutowireCapableBeanFactory().autowireBean(this);
        // springBeanName is now available.
    }
}

If I autowire repository class, everything works well, but if I autowire service class as the code above, the error occurs. Here is the full error stack:

com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean loginBean
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:227)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
    at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    at javax.faces.component.UIInput.getValue(UIInput.java:291)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:94)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:58)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeMarkup(InputTextRenderer.java:71)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeEnd(InputTextRenderer.java:52)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312)
    at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
    at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:206)
    at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:123)
    at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:58)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.sun.faces.spi.InjectionProviderException: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting invoke lifecycle  method public void com.peter.uass.bean.LoginBean.init()
    at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:231)
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
    ... 71 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting invoke lifecycle  method public void com.peter.uass.bean.LoginBean.init()
    at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:393)
    at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:306)
    at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:229)
    ... 72 more
Caused by: java.security.PrivilegedActionException: java.lang.reflect.InvocationTargetException
    at java.security.AccessController.doPrivileged(Native Method)
    at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:376)
    ... 74 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.faces.integration.GlassFishInjectionProvider$2.run(GlassFishInjectionProvider.java:382)
    ... 76 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.peter.uass.bean.LoginBean': Unsatisfied dependency expressed through field 'accountService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.peter.uass.service.AccountService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBean(AbstractAutowireCapableBeanFactory.java:303)
    at com.peter.uass.bean.LoginBean.init(LoginBean.java:38)
    ... 81 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.peter.uass.service.AccountService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 86 more

and this is my service class
AccountService.java

@Service
@Transactional(readOnly = true)
public class AccountService
{
    //@ManagedProperty("#{accountRepository}")
    @Autowired
    private AccountRepository accountRepository;

    public AccountRepository getRepository()
    {
        return accountRepository;
    }

    public void save(Account entity) 
    {
        accountRepository.save(entity);
    }
}

This is my project structure
enter image description here

I am using javaconfig to configure, this is my configuration:
PersistenceContext.java

@Configuration
@EnableJpaRepositories(basePackages ={"com.peter.uass"})
//@EnableJpaRepositories(basePackages ={"com.peter.uass.repository", "com.peter.uass.service"})
//@EnableJpaRepositories("com.peter.uass.repository")
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistenceContext
{
    @Bean(destroyMethod = "close")
    DataSource dataSource(Environment env)
    {
        HikariConfig dataSourceConfig = new HikariConfig();
        dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
        dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
        dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
        dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));

        return new HikariDataSource(dataSourceConfig);
    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env)
    {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.peter.uass");

        Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
        jpaProperties.put("hibernate.ejb.naming_strategy", env.getRequiredProperty("hibernate.ejb.naming_strategy"));
        jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
        jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory)
    {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
}

my WebAppInitializer.java is empty, I use web.xml to configure.
web.xml

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.peter.uass.config</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
Newbie
  • 1,584
  • 9
  • 33
  • 72
  • 1
    it clearly says org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.peter.uass.service.AccountService' available. Please ensure it is getting scanned. share the package structure to find out the problem – Barath Jul 23 '17 at 09:10
  • @Barath how to make sure it is scanned? any guide? sorry I am new in JSF and Spring. I have updated the question to include my project structure – Newbie Jul 23 '17 at 09:16
  • Please check for the component scan attribute in applicationContext.xml as mentioned in this example https://www.mkyong.com/jsf2/jsf-2-0-spring-integration-example/. ensure your service packages are also gets scanned. – Barath Jul 23 '17 at 09:20
  • please add the WebAppInitilalizer, there are probably the scanned packages configured – Turo Jul 23 '17 at 09:22
  • @Barath I have updated my java config, I have tried to include multiple packages instead of include only root package, but both doesn't work. – Newbie Jul 23 '17 at 09:32
  • @Turo I have included my configuration and web.xml, please have a look, my WebAppInitilalizer is empty since I configure it inside web.xml – Newbie Jul 23 '17 at 09:33
  • contextConfigLocation should point to the location of the configuration file. see this https://stackoverflow.com/questions/27539610/order-of-loading-contextconfiglocation-in-web-xml-of-spring-servlet-project – Barath Jul 23 '17 at 09:36
  • 1
    see this example https://stackoverflow.com/questions/27539610/order-of-loading-contextconfiglocation-in-web-xml-of-spring-servlet-project add applicationContext.xml and refer to the correct packages. it will resolve the issue or add @ComponentScan annotation at the correct place – Barath Jul 23 '17 at 09:39
  • @Barath applicationContext.xml is necessary for this application? since I am using java config already, which is my PersistenceContext.java, and my contextConfigLocation already point to the configuration file's location. – Newbie Jul 23 '17 at 13:55
  • 1
    if it scans PersisentenceContext then add @ComponentScan("your packages here") – Barath Jul 23 '17 at 14:03
  • Possible duplicate of [Spring JSF integration: how to inject a Spring component/service in JSF managed bean?](https://stackoverflow.com/questions/18387993/spring-jsf-integration-how-to-inject-a-spring-component-service-in-jsf-managed) – Kukeltje Jul 23 '17 at 15:21
  • @Barath thank you, it works after I add in `@ComponentScan`. Thank you so much. – Newbie Jul 23 '17 at 16:04
  • try not to mix jsf annotations with spring annotations. If you wanna use Autowired, use Component instead of @ManagedBean – DaviM Jun 04 '18 at 17:55

0 Answers0