Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/validation/ValidatorFactory
Resolving Spring Context Initialization Error: NoClassDefFoundError for ValidatorFactory
The root cause of this issue is a java.lang.NoClassDefFoundError for the javax/validation/ValidatorFactory class.
This error usually occurs when there’s a missing dependency in your project. In this case, it’s likely that you’re missing the Java Validation API (JSR 303) dependency. To resolve this issue, you need to include the appropriate dependency in your project.
Solution 1: Add Java Validation API Dependency
If you’re using Maven, add the following dependency to your pom.xml file:
javax.validationvalidation-api2.0.1.Final
If you’re using Gradle, add the following dependency to your build.gradle file:
After adding the dependency, rebuild your project and the error should be resolved.
Solution 2: Check for Classpath Issues
If the issue persists after adding the Java Validation API dependency, there might be a problem with your project’s classpath. Check your project’s classpath settings to ensure that all required libraries are included and properly configured. You can also try cleaning and rebuilding your project to ensure that the classpath settings are updated.
Ensure that your Spring configuration files (e.g., applicationContext.xml or any other XML configuration files) are correctly set up. Verify that the correct bean definitions, namespaces, and schema locations are specified. Additionally, double-check that the sessionFactory bean is correctly configured, and there are no typos or incorrect settings.
After addressing the issue, rebuild and restart your application to see if the error has been resolved. If you still encounter issues, double-check your project configuration and ensure that all required dependencies are included.
Exception encountered during context initialization — cancelling refresh attempt
In this article, we are discussing the Spring org.springframework.beans.factory. NoUniqueBeanDefinitionException — this is a common exception thrown by the BeanFactory when it is unable to set the property of any bean.
Description
Exception thrown on an attempt to set the value of a property that is not writable (typically because there is no setter method)
Complete Exception Stack Trace
WARNING: Exception encountered during context initialization — cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘daoBean’ defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘name’ of bean class [dao.CoreDao]: Bean property ‘name’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? Exception in thread «main» org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘daoBean’ defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘name’ of bean class [dao.CoreDao]: Bean property ‘name’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1642) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1357) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:578) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) at org.springframework.context.support.ClassPathXmlApplicationContext. (ClassPathXmlApplicationContext.java:144) at org.springframework.context.support.ClassPathXmlApplicationContext. (ClassPathXmlApplicationContext.java:85) at test.Test.main(Test.java:12) Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property ‘name’ of bean class [dao.CoreDao]: Bean property ‘name’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243) at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426) at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278) at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1638) . 13 more
Let’s see when this Exception occurs with an Example:
Java – How to solve this : Exception encountered during context initialization – cancelling refresh attempt
I am new to spring and hibernate and trying to create simple webapp. but i am stuck on this error for several days. When I tried to run junit test this error is showing. what am i missing here?
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
@Configuration @ComponentScan(basePackages = ) @EnableTransactionManagement public class HibernateConfig < // change the below based on the DBMS you choose private final static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/onlineshopping"; private final static String DATABASE_DRIVER = "org.h2.Driver"; private final static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect"; private final static String DATABASE_USERNAME = "sa"; private final static String DATABASE_PASSWORD = ""; // database bean will be available @Bean public DataSource getDataSource() < BasicDataSource dataSource = new BasicDataSource(); // providing the database connection information dataSource.setDriverClassName(DATABASE_DRIVER); dataSource.setUrl(DATABASE_URL); dataSource.setUsername(DATABASE_USERNAME); dataSource.setPassword(DATABASE_PASSWORD); return dataSource; >// sessionFactory bean will be available public SessionFactory getSessionFactory(DataSource dataSource) < LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource); builder.addProperties(getHibernateProperties()); builder.scanPackages("net.kzn.shoppingbackend.dto"); return builder.buildSessionFactory(); >// All the hibernate properties will be returned in this method private Properties getHibernateProperties() < Properties properties = new Properties(); properties.put("hibernate.dialect", DATABASE_DIALECT); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.format_sql", "true"); return properties; >// transactionManager bean public HibernateTransactionManager geTransactionManager(SessionFactory sessionFactory) < HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory); return transactionManager; >>
CategoryTestCase.java
public class CategoryTestCase < private static AnnotationConfigApplicationContext context; private static CategoryDAO categoryDAO; private Category category; @BeforeClass public static void init() < context = new AnnotationConfigApplicationContext(); context.scan("net.kzn.shoppingbackend"); context.refresh(); categoryDAO = (CategoryDAO) context.getBean("categoryDAO"); >@Test public void testAddCategory() < category = new Category(); category.setName("Television"); category.setDescription("This is some description for television"); category.setImageurl("CAT_1.png"); assertEquals("successfully added a category inside the table!", true, categoryDAO.add(category)); >>
I go through other similar questions but that dosen’t help.
Best Solution
Adding @Bean to SessionFactory has resolved the issue,
// sessionFactory bean will be available @Bean public SessionFactory getSessionFactory(DataSource dataSource)
Related Solutions
Spring Security with Openid and Database Integration
As I see that question text itself contains the answer. I am just pulling it out and posting it as the answer for the sake of clarity to other developers with the same problem. It took me a while to figure out that question has the answer!
To access user email & name, you need to add below configuration in the security xml file.
Thereafter, it will be accessible in the AuthenticationUserDetailsService class, as shown below.
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) < String : : List attributes = token.getAttributes(); for (OpenIDAttribute attribute : attributes) < if (attribute.getName().equals("email")) < email = attribute.getValues().get(0); >if (attribute.getName().equals("firstName")) < firstName = attribute.getValues().get(0); >if (attribute.getName().equals("lastName")) < lastName = attribute.getValues().get(0); >if (attribute.getName().equals("fullname")) < fullName = attribute.getValues().get(0); >> : : // form and return user object >
Considering that we use more of Java-based configuration/beans now, translating these XML configuration to Java-based configuration shouldn’t be a problem.
Java – How to solve the “failed to lazily initialize a collection of role” Hibernate exception
If you know that you’ll want to see all Comment s every time you retrieve a Topic then change your field mapping for comments to: