- 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
- Solution 1: Add Java Validation API Dependency
- Solution 2: Check for Classpath Issues
- Solution 3: Verify Configuration Files
- Exception encountered during context initialization — cancelling refresh attempt
- Description
- Complete Exception Stack Trace
- Java – How to solve this : Exception encountered during context initialization – cancelling refresh attempt
- Best Solution
- Related Solutions
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.validation validation-api 2.0.1.Final
If you’re using Gradle, add the following dependency to your build.gradle file:
implementation 'javax.validation:validation-api:2.0.1.Final'
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.
Solution 3: Verify Configuration Files
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:
my entity class
Category.java
@Entity public class Category < /* * private fields */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String description; @Column(name = "img_url") private String imageurl; @Column(name = "is_active") private boolean active = true; /* * getters and setters */ 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 String getDescription() < return description; >public void setDescription(String description) < this.description = description; >public String getImageurl() < return imageurl; >public void setImageurl(String imageurl) < this.imageurl = imageurl; >public boolean isActive() < return active; >public void setActive(boolean active) < this.active = active; >@Override public String toString() < return "Category [id=" + id + ", name=" + name + ", description=" + description + ", imageurl=" + imageurl + ", active=" + active + "]"; >>
PageController.java
@Controller public class PageController < @Autowired private CategoryDAO categoryDAO; @RequestMapping(value = < "/", "/home", "/index" >) public ModelAndView index() < ModelAndView mv = new ModelAndView("page"); mv.addObject("title", "home"); //passing the list of categories mv.addObject("categories", categoryDAO.list()); mv.addObject("userClickHome", true); return mv; >@RequestMapping(value = < "/about" >) public ModelAndView about() < ModelAndView mv = new ModelAndView("page"); mv.addObject("title", "About us"); mv.addObject("userClickAbout", true); return mv; >@RequestMapping(value = < "/contact" >) public ModelAndView contact() < ModelAndView mv = new ModelAndView("page"); mv.addObject("title", "Contact us"); mv.addObject("userClickContact", true); return mv; >@RequestMapping(value = "/show/all/products") public ModelAndView showAllProducts() < ModelAndView mv = new ModelAndView("page"); mv.addObject("title", "All products"); //passing the list of categories mv.addObject("categories", categoryDAO.list()); mv.addObject("userClickAllProducts", true); return mv; >@RequestMapping(value = "/show/category//products") public ModelAndView showCategoryProducts(@PathVariable("id") int id) < ModelAndView mv = new ModelAndView("page"); // categoryDAO to fetch a single category Category category = null; category = categoryDAO.get(id); mv.addObject("title", category.getName()); //passing the list of categories mv.addObject("categories", categoryDAO.list()); //passing the list of category object mv.addObject("category", category); mv.addObject("userClickCategoryProducts", true); return mv; >>
CategoryDAOimpl.java
@Repository("categoryDAO") public class CategoryDAOImpl implements CategoryDAO < @Autowired private SessionFactory sessionFactory; private static Listcategories = new ArrayList<>(); //private static CategoryDAO categoryDAO; static < Category category = new Category(); // first category category.setId(1); category.setName("Television"); category.setDescription("This is some description for television"); category.setImageurl("CAT_1.png"); categories.add(category); // second category category = new Category(); category.setId(2); category.setName("Mobile"); category.setDescription("This is some description for mobile"); category.setImageurl("CAT_2.png"); categories.add(category); // third category category = new Category(); category.setId(3); category.setName("laptop"); category.setDescription("This is some description for laptop"); category.setImageurl("CAT_3.png"); categories.add(category); >@Override public List list() < // TODO Auto-generated method stub return categories; >@Override public Category get(int id) < //ecnhanced for loop for(Category category : categories) < if(category.getId() == id) return category; >return null; > @Override @Transactional public boolean add(Category category) < try < //add the category to the database table sessionFactory.getCurrentSession().persist(category); return true; >catch (Exception e) < e.printStackTrace(); return false; >> >
interface
CategoryDAO.java
@Service public interface CategoryDAO < Listlist(); Category get(int id); boolean add(Category category); >
HibernateConfig.java
@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)); >>
4.0.0 net.kzn shoppingbackend 0.0.1-SNAPSHOT jar shoppingbackend http://maven.apache.org UTF-8 4.3.19.RELEASE 5.2.7.Final junit junit 4.12 test org.springframework spring-context $ org.springframework spring-orm $ com.h2database h2 1.4.197 org.hibernate hibernate-core $ dom4j dom4j org.apache.commons commons-dbcp2 2.1.1 maven-compiler-plugin 3.1 1.8
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:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL) private Collection comments = new LinkedHashSet();
Collections are lazy-loaded by default, take a look at this if you want to know more.