How can i create bean entityManagerFactoryBean in java multimodule project? - java

entityManagerFactoryBean
2016-02-13 20:38:22 WARN XmlWebApplicationContext:546 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [5]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'UserDetailsServiceImplementation' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserDetailsServiceImplementation' defined in ServletContext resource [/WEB-INF/spring-security.xml]: Cannot resolve reference to bean 'jpaUserDao' while setting bean property 'adminUserDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaUserDao' defined in ServletContext resource [/WEB-INF/spring-security.xml]: Cannot resolve reference to bean 'entityManagerFactoryBean' while setting bean property 'entityManagerFactoryBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactoryBean' is defined
2016-02-13 20:38:22 ERROR ContextLoader:353 - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [5]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'UserDetailsServiceImplementation' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserDetailsServiceImplementation' defined in ServletContext resource [/WEB-INF/spring-security.xml]: Cannot resolve reference to bean 'jpaUserDao' while setting bean property 'adminUserDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaUserDao' defined in ServletContext resource [/WEB-INF/spring-security.xml]: Cannot resolve reference to bean 'entityManagerFactoryBean' while setting bean property 'entityManagerFactoryBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactoryBean' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:382)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
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:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4812)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
spring-security.xml lies in web directory
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/adm/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/red/**" access="hasAnyRole('ROLE_ADMIN', 'ROLE_REDADMIN')" />
<intercept-url pattern="/**" access="permitAll" />
<!-- access denied page -->
<access-denied-handler error-page="/index" />
<form-login login-page="/login" default-target-url="/index"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="email"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<csrf />
</http>
<beans:bean id="UserDetailsServiceImplementation"
class="com.softserveinc.ita.redplatform.business.service.UserDetailsServiceImplementation">
<beans:property name="adminUserDao" ref="jpaUserDao" />
</beans:bean>
<beans:bean id="jpaUserDao"
class="com.softserveinc.ita.redplatform.persistence.dao.impl.JPAAdminUserDao">
<beans:property name="entityManagerFactoryBean" ref="entityManagerFactoryBean"/>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="UserDetailsServiceImplementation">
</authentication-provider>
</authentication-manager>
persistence-context.xml lies in persistence directory
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<context:component-scan base-package="com.softserveinc.ita.redplatform.persistence.dao.impl" />
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="JPAUnit" />
<property name="packagesToScan">
<list>
<value>com.softserveinc.ita.redplatform.common.entity</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<!-- <bean id="jpaUserDao" class="com.softserveinc.ita.redplatform.persistence.dao.impl.JPAAdminUserDao"> -->
<!-- <property name="managerFactoryBean" ref="entityManagerFactoryBean"/> -->
<!-- </bean> -->
<tx:annotation-driven />
</beans>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>REDplatform</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan
base-package="com.softserveinc.ita.redplatform.web.controller" />
<import resource="classpath*:**/spring/*context.xml" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath*:**/properties/*properties</value>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<ref bean="realEstateAgencyDTOFormatter" />
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService" />
<mvc:resources mapping="/resources/**" location="/resources/" />
JPAAdminUserDao class have method findUserByEmail
#Transactional
public class JPAAdminUserDao extends JPAGenericDao<AdminUser, Long>
implements AdminUserDao {
#Autowired
private EntityManager entityManagerFactoryBean;
/**
*
* #param email receiving
* #return AdminUser object
*/
public final AdminUser findUserByEmail(final String email) {
List<AdminUser> users = new ArrayList<AdminUser>();
users = (List<AdminUser>)entityManagerFactoryBean.getEntityManagerFactory().createEntityManager()
.createQuery("from " + AdminUser.class.getName()
+ " as user where user.email=:email")
.setParameter("email", email).getResultList();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
}
UserDetailsServiceImplementation
public class UserDetailsServiceImplementation implements UserDetailsService {
/**
* Using JPAAdminUserDao object.
*/
#Autowired
private JPAAdminUserDao jpaUserDao;
#Override
public final UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
HashSet<String> set = new HashSet<String>();
AdminUser user = (AdminUser) jpaUserDao.findUserByEmail(username);
if (user instanceof AdminUser) {
set.add(new String("ROLE_USER"));
set.add(new String("ROLE_ADMIN"));
set.add(new String("ROLE_REDADMIN"));
} else {
set.add(new String("ROLE_USER"));
}
List<GrantedAuthority> authorities = buildUserAuthority(set);
return buildUserForAuthentication(user, authorities);
}
/**
*
* #param user Receiving user object
* #param authorities Receiving list of user authorities
* #return returning user object
*/
private User buildUserForAuthentication(final AdminUser user,
final List<GrantedAuthority> authorities) {
return new User(user.getEmail(), user.getPassword(), true,
true, true, true, authorities);
}
/**
*
* #param userRoles receiving
* #return Returning list of authorities
*/
private List<GrantedAuthority> buildUserAuthority(final
Set<String> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (String userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole));
}
List<GrantedAuthority> result = new
ArrayList<GrantedAuthority>(setAuths);
return result;
}
public final JPAAdminUserDao getJpaUserDao() {
return jpaUserDao;
}
public final void setAdminUserDao(final JPAAdminUserDao newJpaUserDao) {
this.jpaUserDao = newJpaUserDao;
}
}
If i comment next line
<beans:property name="entityManagerFactoryBean" ref="entityManagerFactoryBean"/>
in spring-security I will have java.lang.NullPointerException in JPAAdminUserDao class in method findUserByEmail

You seem to have problems while you are loading your spring xml beans configuration files. Your persistence-context.xml is probably never loaded.
Are you sure that this line is importing the persistence-context.xml file (Remove it if it is no longer necessary, it may load some context twice) :
<import resource="classpath*:**/spring/*context.xml" />
Try to add the persistence-context.xml in the context-param in your web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
**/path/to/persistence-context.xml
</param-value>
</context-param>
To ensure that your servlet-context.xml file is correctly loaded, add an init param to your DispatcherServlet declaration in your web.xml :
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/path/to/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Related

Problem with spring-database xml config after upgrading to Hibernate 5 and Spring 5

I upgraded my application from Java7 to Java8, Spring 3.4 to Spring 5.1.4, Hibernate 4.2.11 to 5.2.11.
I checked the jars and I have updated spring jars (v5.1.4) and hibernate jars (5.2.11).
Resolved POM
<properties>
<spring.security.version>5.1.3.RELEASE</spring.security.version>
<slf4j.version>1.7.25</slf4j.version>
<dbcp.version>1.4</dbcp.version>
<java-version>1.8</java-version>
<jstl.version>1.2</jstl.version>
<displaytag.version>1.2</displaytag.version>
<hibernate.version>5.2.11.Final</hibernate.version>
<logback.version>1.1.2</logback.version>
<jspapi.version>2.1</jspapi.version>
<servletapi.version>2.5</servletapi.version>
<jackson.version>1.9.10</jackson.version>
<mysql.connector.version>8.0.13</mysql.connector.version>
<spring.version>5.1.4.RELEASE</spring.version>
</properties>
spring-database.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.s382.kris.*" />
<tx:annotation-driven />
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/s382?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="admin" />
<property name="password" value="admin" />
</bean>
<!-- Hibernate 5 XML SessionFactory Bean definition-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>orm/User.hbm.xml</value>
<value>orm/UserRole.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<!-- MUST have transaction manager, using aop and aspects -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allServices" expression="execution(* com.s382.kris.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServices" />
</aop:config>
'''
Stack Trace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'companyController' defined in file [/home/barkha/Documents/workspace-sts-3.9.7.RELEASE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/s382/WEB-INF/classes/com/s382/kris/controller/CompanyController.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot resolve reference to bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' while setting bean property 'transactionAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.methodSecurityMetadataSourceAdvisor': Cannot resolve reference to bean 'org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource#0': Cannot create inner bean '(inner bean)#348f470f' of type [org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource] while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#348f470f': Cannot create inner bean '(inner bean)#3de1ec44' of type [org.springframework.security.access.expression.method.ExpressionBasedAnnotationAttributeFactory] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3de1ec44': Cannot resolve reference to bean 'org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParser$DefaultMethodSecurityExpressionHandlerBeanFactory#0$created#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParser$DefaultMethodSecurityExpressionHandlerBeanFactory#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: ; nError creating bean with name 'sessionFactory': Lookup method resolution failedested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.orm.hibernate5.LocalSessionFactoryBean] from ClassLoader [ParallelWebappClassLoader
Application builds successfully but throws error on launching on tomcat9

No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined

I using Spring + Hibernate + JPA and Tomcat 7 for REST service. When I start the app I get the following:
org.apache.catalina.core.ApplicationContext log org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainController': Unsatisfied dependency expressed through field 'carService': Error creating bean with name 'carServiceImpl': Unsatisfied dependency expressed through field 'carDao': Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'carServiceImpl': Unsatisfied dependency expressed through field 'carDao': Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'carServiceImpl': Unsatisfied dependency expressed through field 'carDao': Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
Below i show my spring config class
#Configuration
#Import(DispatcherServletConfig.class)
#ComponentScan(basePackages = "org.parkingTracker.controller, org.parkingTracker.service, org.parkingTracker.dao")
#ImportResource("classpath*:/dao/src/main/resources/spring/dao-context.xml")
public class RootConfig {
public RootConfig() {}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "org.parkingTracker.controller, org.parkingTracker.service")
public class DispatcherServletConfig {
public DispatcherServletConfig() {}
}
I also have service and dao classes for access to data. To inject EntityManager in my dao i am using #PersistenceContext annotation, for inject dao for service class i am using simple spring annotations. Below you can see my spring xml config for DAO layout. One important comments, when i run test for dao classes all passing right, and i don't have any Exceptions, and i am obtaining valid data
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa = "http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">
<context:component-scan base-package="org.parkingTracker.dao"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/parking"/>
<property name="username" value="postgres"/>
<property name="password" value="a1f10g"/>
<property name="initialSize" value="20"/>
<property name="maxActive" value="100"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
</bean>
</property>
<property name="packagesToScan" value="org.parkingTracker.model"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL94Dialect</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<jpa:repositories base-package="org.parkingTracker"
entity-manager-factory-ref="emf"
transaction-manager-ref="transactionManager"/></beans>
CarServiceImpl:
public class CarServiceImpl implements CarService {
#Autowired
private CarDao carDao;
#Override
public void saveCar(Car car) throws EntityAlreadyExistException {
carDao.saveCar(car);
}
#Override
public Car getCarById(int id) {
return carDao.getCarById(id);
}
#Override
public Car getCarByIdWithTimeSpend(int id) {
return carDao.getCarByIdWithTimeSpend(id);
}
#Override
public Car getCarByNumber(String number) {
return carDao.getCarByNumber(number);
}
#Override
public Car getCarByNumberWithTimeSpend(String number) {
return carDao.getCarByNumberWithTimeSpend(number);
}
CarDao:
#Transactional
#Repository("carDao")
public class CarDaoImp implements CarDao{
private final String EXIST_SQL = "SELECT 1 FROM car WHERE car_num = :num";
#PersistenceContext
private EntityManager entityManager;
#Transactional()
public void saveCar(Car car) throws EntityAlreadyExistException {
if(entityManager.createNativeQuery(EXIST_SQL).setParameter("num", car.getNumber()).getSingleResult()!=null){
throw new EntityAlreadyExistException();
}else {
entityManager.persist(car);
}
}
#Transactional(readOnly = true)
public Car getCarById(int id) {
return entityManager.find(Car.class, id);
}
#Transactional(readOnly = true)
public Car getCarByIdWithTimeSpend(int id) {
Car car = entityManager.find(Car.class, id);
Hibernate.initialize(car.getTimeSet());
return car;
}
#Override
#Transactional(readOnly = true)
public Car getCarByNumber(String number) throws NoResultException{
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Car> carCriteriaQuery = entityManager.getCriteriaBuilder().createQuery(Car.class);
Root<Car> root = carCriteriaQuery.from(Car.class);
carCriteriaQuery.select(root);
carCriteriaQuery.where(builder.equal( root.get(Car_.number), number ));
return entityManager.createQuery(carCriteriaQuery).getSingleResult();
}
#Override
#Transactional(readOnly = true)
public Car getCarByNumberWithTimeSpend(String number){
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Car> carCriteriaQuery = entityManager.getCriteriaBuilder().createQuery(Car.class);
Root<Car> root = carCriteriaQuery.from(Car.class);
carCriteriaQuery.select(root);
carCriteriaQuery.where(builder.equal( root.get(Car_.number), number ));
Car car = entityManager.createQuery(carCriteriaQuery).getSingleResult();
Hibernate.initialize(car.getTimeSet());
return car;
}
}
web.xml :
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<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>
org.parkingTracker.controller.config.RootConfig
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
org.parkingTracker.controller.config.DispatcherServletConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
It seems that IOC container is failing to inject the EntityManagerFactory
to CarDaoImp. I looked at your code and it seems that you defined all the necessary configurations, I think the problem lies down with your XML configuration file loading.
Try to use classpath:your_xml_config.xml, with out the folder structure prefix. like this:
#Configuration
#Import(DispatcherServletConfig.class)
#ComponentScan(basePackages = "org.parkingTracker.controller, org.parkingTracker.service, org.parkingTracker.dao")
#ImportResource("classpath:dao-context.xml")
public class RootConfig {
public RootConfig() {}
}

Spring Security: Unable to autowired DAO in the UserDetailsService class

This question has been asked many times, and I tired many solutions but failed.
I'm trying to map the users to the Spring Security users. My security.xml is able to see my userDao class. I do not understand why I couldn't autowired my class.
My spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.memorize" />
<!-- This is where we configure Spring-Security -->
<security:http auto-config="true" use-expressions="true" access-denied-page="/memorize/auth/403" >
<security:intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<security:form-login
login-page="/memorize/auth/login"
authentication-failure-url="/memorize/auth/login?error=true"
default-target-url="/memorize/movie/sp"/>
<security:logout
invalidate-session="true"
logout-success-url="/memorize/login"
logout-url="/memorize/movie/sps"/>
</security:http>
<!-- Declare an authentication-manager to use a custom userDetailsService -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
</beans>
I am scanning all my components by this tag:
<context:component-scan base-package="com.memorize" />
This is my springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.memorize" />
<mvc:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/springdb" />
<property name="username" value="xxx" />
<property name="password" value="xxx" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>/mappings/Users.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="usersDAO" class="com.memorize.dao.impl.UsersDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="customUserDetailsService" class="com.memorize.service.CustomUserDetailsService">
<property name="usersDAO" ref="usersDAO" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
And this is my CustomUserDetailsService class
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UsersDAO usersDAO;
And the error is this:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.service.UsersService com.memorize.controller.UsersController.usersService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.service.UsersService com.memorize.controller.UsersController.usersService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 38 more
My UsersDao class
public interface UsersDAO {
void saveOrUpdate(Users user);
Users find(int userId);
}
My UsersDAOImpl is:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.memorize.dao.UsersDAO;
import com.memorize.model.Users;
public class UsersDAOImpl implements UsersDAO {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Users u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
}
#Override
public void saveOrUpdate(Users user) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
#Override
public Users find(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
return (Users) session.get(Users.class, id);
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4">
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
        
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/memorize/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
UPDATE
After the suggestions, I changed my UsersDAOImpl as this:
My UsersDAOImpl is:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.memorize.dao.UsersDAO;
import com.memorize.model.Users;
#Repository
public class UsersDAOImpl implements UsersDAO {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Users u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
}
#Override
public void saveOrUpdate(Users user) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
#Override
public Users find(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
return (Users) session.get(Users.class, id);
}
}
However after this change, I get this error:
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.memorize.dao.impl.UsersDAOImpl.sessionFactory;
No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}.
Now I could not autowired my sessionFactory under UsersDAOImpl class.
Add a #Repository annotation to the UsersDAO implementation so the class can be included in the component scan
#Repository
public class UsersDAOImpl implements UsersDAO {
Its right you are scanning com.memorize
<context:component-scan base-package="com.memorize" />
But only the classes with annotations like #controller,#service,#component, #Repository etc will be the candidates for auto wiring and the other classes are not.so consider annotating your class accordingly for proper auto wiring.
#Component --> generic stereotype for any Spring-managed component
#Repository--> stereotype for persistence layer
#Service --> stereotype for service layer
#Controller --> stereotype for presentation layer (spring-mvc)
The following should solve the error.
#Repository
public class UsersDAOImpl implements UsersDAO {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Users u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
}
#Override
public void saveOrUpdate(Users user) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
#Override
public Users find(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
return (Users) session.get(Users.class, id);
}
}
I believe that the problem with your config is that UserDao bean if defined in different context (servlet's one). Same goes to SessionFactory, it won't be autowired. My suggestion is to move common beans to root-context, which is loaded in both servlet's and securitie's context.
An example:
root-context.xml
In root context I'm autowiring (by component scan) every bean that is not a #Controller
<context:component-scan base-package="pl.com.suadeo.nwfm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="regex" expression="pl.com.suadeo.nwfm.webservice.*"/>
</context:component-scan>
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/application.properties</value>
</list>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="${dataSource.name}"/>
<property name="packagesToScan" value="pl.com.suadeo.nwfm.models"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${sessionFactory.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${sessionFactory.hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${sessionFactory.hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${sessionFactory.hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.import_files">${sessionFactory.hibernate.import_files}</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
<!---->
<!--MESSAGE SOURCE-->
<!---->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"/>
<property name="basenames">
<list>
<value>/WEB-INF/message/labels</value>
<value>/WEB-INF/message/form-errors</value>
<value>/WEB-INF/message/messages</value>
</list>
</property>
<property name="useCodeAsDefaultMessage" value="${messageSource.useCodeAsDefaultMessage}"/>
<property name="fallbackToSystemLocale" value="true"/>
<property name="cacheSeconds" value="${messageSource.cacheSeconds}"/>
</bean>
</beans>
servlet-context.xml
In servlet context, I'm scanning for #Controller annotation, enabling spring security and set up some other revelant to servlet config
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="pl.com.suadeo.nwfm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/fonts/" mapping="/fonts/**"/>
<mvc:resources location="/favicon.ico" mapping="/favicon.ico"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/static/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/application.properties</value>
</list>
</property>
</bean>
<!---->
<!--MULTIPART RESOLVER-->
<!---->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52428800"/>
<property name="maxInMemorySize" value="52428800"/>
</bean>
<!---->
<!--SPRING SECURITY-->
<!---->
<security:global-method-security proxy-target-class="true" pre-post-annotations="enabled"/>
</beans>
security-context.xml
In security context, I'm able to see beans from root context, so no need for additional component scan
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http pattern="/services/**" security="none"/>
<http pattern="/css/**" security="none"/>
<http pattern="/img/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/fonts/**" security="none"/>
<http pattern="/favicon.ico" security="none"/>
<http pattern="/settings/fontSize" security="none"/>
<http auto-config="false" use-expressions="true">
<intercept-url pattern="/login*" access="permitAll()"/>
<intercept-url pattern="/register*" access="permitAll()"/>
<intercept-url pattern="/qualification/tree*/**" access="permitAll()"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-processing-url="/processLogin" username-parameter="email" password-parameter="password"
default-target-url="/" always-use-default-target="false" login-page="/login" authentication-failure-url="/login?error=true"/>
<logout logout-url="/logout" logout-success-url="/"/>
</http>
<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="daoAuthenticationProvider"/>
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsService" class="pl.com.suadeo.nwfm.security.UserDetailsServiceImpl"/>
</beans:beans>
UserServiceImpl.java
Then in you UserServiceImpl, you may autowire your beans:
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Autowired
private UserService userService;
public UserDetails loadUserByUsername( String email ) throws UsernameNotFoundException, DataAccessException {
User userEntity = userRepository.findByEmail( email );
if ( userEntity == null ) {
throw new UsernameNotFoundException( "user not found" );
}
return userService.buildUserFromUserEntity( userEntity );
}
}
Hope this will help

Cannot create bean when start the application

I am facing some issue while creating the bean it gives error.
Can someone please assist me. I will retrieve the files from sftp resource and will read those file with a spring task scheduler job.
App-Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/sftp
http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd">
<context:component-scan base-package="com.canaldigital.tsi.bank" />
<context:property-placeholder location="classpath:settings.properties" />
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="myBean" method="printMessage" fixed-delay="600000" initial-delay="3000"/>
<task:scheduled ref="myBean" method="checkStatus" fixed-delay="6000" initial-delay="2000"/>
</task:scheduled-tasks>
<task:scheduler id="myScheduler" pool-size="10" />
<bean id="sftpSessionFactory" class="org.springframework.integration.file.remote.session.CachingSessionFactory">
<constructor-arg ref="defaultSftpSessionFactory" />
<property name="sessionCacheSize" value="10"/>
<property name="sessionWaitTimeout" value="1000"/>
</bean>
<bean id="defaultSftpSessionFactory"
class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
<property name="host" value="${sftp.host}"/>
<property name="username" value="${sftp.username}"/>
<property name="password" value="${sftp.password}"/>
<property name="port" value="${sftp.serverPort}"/>
<!-- <property name="privateKey" value="${sftp.private.keyfile}"/> -->
<!-- <property name="privateKeyPassphrase" value="${sftp.passphrase}"/> -->
</bean>
<int-sftp:inbound-channel-adapter id="sftpAdapterAutoCreate"
session-factory="sftpSessionFactory"
channel="requestChannel"
filename-pattern="*.csv"
remote-directory="/home/oracle/IBSTOBANK/DNB/Norway/Outgoing"
preserve-timestamp="true"
local-directory="file:target/foo"
auto-create-local-directory="true"
local-filename-generator-expression="#this.toUpperCase() + '.a'"
local-filter="myFilter"
temporary-file-suffix=".writing"
delete-remote-files="false">
<int:poller fixed-rate="1000"/>
</int-sftp:inbound-channel-adapter>
<int:channel id="requestChannel">
<int:queue/>
</int:channel>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
</bean>
<!-- Defining a datasource -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<description>This is JNDI based Data Source.</description>
<property name="jndiName">
<value>jdbc/BIZLOGDS</value>
</property>
</bean> -->
<!-- Definition for JDBCTemplate bean -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="TransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
StackTrace:
org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler shutdown
INFO: Shutting down ExecutorService 'myScheduler'
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sftpSessionFactory' defined in class path resource [app-config.xml]: Cannot resolve reference to bean 'defaultSftpSessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultSftpSessionFactory' defined in class path resource [app-config.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'sftp' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:646)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:140)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1114)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1017)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.canaldigital.tsi.bank.config.AppMain.main(AppMain.java:16)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultSftpSessionFactory' defined in class path resource [app-config.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'sftp' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 17 more
Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'sftp' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:146)
at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1362)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:214)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 23 more
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'sftp' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:215)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:85)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:78)
at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:48)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:84)
at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:103)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:94)
at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:143)
... 29 more
please visit DefaultSftpSessionFactory
it has following :
setUser
public void setUser(String user)
The remote user to use. This is a mandatory property.
Parameters:
user - The user.
See Also:
JSch.getSession(String, String, int)

"No Persistence Unit Found" error

I am getting the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor': Cannot create inner bean '(inner bean)' while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'txManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txManager' defined in class path resource [persistenceLayer.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [persistenceLayer.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'CounterpartContacts' found
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'txManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txManager' defined in class path resource [persistenceLayer.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [persistenceLayer.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'CounterpartContacts' found
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txManager' defined in class path resource [persistenceLayer.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [persistenceLayer.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'CounterpartContacts' found
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [persistenceLayer.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'CounterpartContacts' found
Caused by: java.lang.IllegalArgumentException: No persistence unit with name 'CounterpartContacts' found
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:337)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:219)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:185)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:237)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1062)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1029)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:420)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:245)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:141)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:242)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:156)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:246)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:128)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:955)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:729)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:416)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:245)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:141)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:242)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:156)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:246)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:128)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:955)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:729)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:416)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBeanDefinition(BeanDefinitionValueResolver.java:198)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:955)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:729)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:416)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:245)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:141)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:242)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:156)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:102)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:68)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:54)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:247)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:311)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1038)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:420)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:245)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:141)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:242)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:156)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:290)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:348)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:92)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:77)
at com.apollo.counterpartcontacts.service.PersistenceManagerTest.beforeClass(PersistenceManagerTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:537)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:206)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:132)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:173)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.runWorkers(TestRunner.java:1182)
at org.testng.TestRunner.privateRun(TestRunner.java:761)
at org.testng.TestRunner.run(TestRunner.java:612)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:335)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:330)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:292)
at org.testng.SuiteRunner.run(SuiteRunner.java:241)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1169)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1094)
at org.testng.TestNG.run(TestNG.java:1006)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:107)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:199)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:170)
Here is my persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="CounterpartContacts">
<jta-data-source>java:/comp/env/jdbc/CounterpartContact</jta-data-source>
<class>com.counterpartcontacts.entity.AgentContact</class>
<class>com.counterpartcontacts.entity.SecurityContact</class>
<class>com.counterpartcontacts.entity.Bank</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
</properties>
</persistence-unit>
</persistence>
Here is my persistenceLayer.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="persistenceManager" class="com.apollo.counterpartcontacts.service.PersistenceManager">
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<!-- <context:annotation-config /> -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="CounterpartContactDataSource" />
<property name="persistenceUnitName" value="CounterpartContacts" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
</beans>
The persistence.xml is located in src/META-INF, which is in the build path, so it should be found properly. Anyone have any ideas?
Well I usually place the persistence.xml in a resources folder /src/main/resouces/META-INF/persistence.xml because I do remember problems in the build not copying the resources to the output-directory.
I just had a look at our configuration and it looks a little different:
<!--
- Drives transactions using local JPA APIs
-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" proxy-target-class="true" />
<!--
Custom PersistenceUnitManager, that reads all persistence.xml files in the
classpath and merges them to one single virtual persistence.xml.
In order to operate properly, all persistence.xml have to define the same
persistence unit name.
-->
<bean id="persistenceUnitManager" class="de.cware.cweb.jpa.MergingPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--
Creates a EntityManagerFactory for use with the Hibernate JPA provider and a simple
in-memory data source populated with test data
-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
<property name="generateDdl" value="true"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${cweb.database.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${cweb.database.generate}</prop>
<prop key="hibernate.search.default.indexBase">${cwb.home}/indexes</prop>
<prop key="hibernate.ejb.naming_strategy">de.cware.cweb.jpa.QuotingNamingStrategy</prop>
</props>
</property>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.ManagedBasicDataSource">
<property name="driverClassName" value="${cweb.database.driver}"/>
<property name="url" value="${cweb.database.url}"/>
<property name="username" value="${cweb.database.user}"/>
<property name="password" value="${cweb.database.password}"/>
<property name="initialSize" value="${cweb.database.initial-pool-size}"/>
<property name="maxIdle" value="${cweb.database.min-pool-size}"/>
<property name="maxActive" value="${cweb.database.max-pool-size}"/>
<property name="validationQuery" value="#{'${cweb.database.validationQuery}}'.length()==0?'':'${cweb.database.validationQuery}'}"/>
<property name="testOnBorrow" value="#{'${cweb.database.validationQuery}}'.length()==0?false:true}"/>
<property name="testWhileIdle" value="#{'${cweb.database.validationQuery}}'.length()==0?false:true}"/>
<property name="timeBetweenEvictionRunsMillis" value="#{'${cweb.database.validationQuery}}'.length()==0?-1:10000}"/>
<property name="minEvictableIdleTimeMillis" value="#{'${cweb.database.validationQuery}}'.length()==0?-1:60000}"/>
<property name="defaultTransactionIsolation" value="#{ T(java.sql.Connection).TRANSACTION_READ_COMMITTED}"/>
</bean>
Hope this helps :-)
Chris
keep your persistence.xml in WEB-INF/classes/META-INF/persistence.xml
remove hibernate conflicting libraries....
remove hibernate - 3.2.0 jar if hibernate core is there
place the persistence.xml in a resources folder /src/main/resouces/META-INF/persistence.xml for me it's work this solution
This error can happen if you have a hibernate mapped class with relations with another non-mapped class, a solution is to check the relation item as #transient (hibernate will ignore it, use this just to check if this is the error, and later map the related class). Example:
#Entity
public class City {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
#Transient
private State state;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
And this is the non-mapped class which may give the error:
public class State {
private String name;
}

Categories