I use this tutorial for Spring MVC example, but I use PostgreSQL.
And I have a lot of exceptions, I have searched but nothing helped.
This is Exception:
SEVERE [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.DispatcherServlet.initServletBean Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.codejava.spring.dao.ContactDAO net.codejava.spring.controller.HomeController.contactDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getContactDAO' defined in class path resource [net/codejava/spring/config/MvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public net.codejava.spring.dao.ContactDAO net.codejava.spring.config.MvcConfiguration.getContactDAO()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getDataSource' defined in class path resource [net/codejava/spring/config/MvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource net.codejava.spring.config.MvcConfiguration.getDataSource()] threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [org.postgresql.Driver]
If I understand right I have a problem with load JDBC Driver, but I already added this in pom.xml
My source code:
MvcConfiguration:
package net.codejava.spring.config;
import javax.sql.DataSource;
import net.codejava.spring.dao.ContactDAO;
import net.codejava.spring.dao.ContactDAOImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan(basePackages="net.codejava.spring")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/contactdb");
dataSource.setUsername("postgres");
dataSource.setPassword("3517571");
return dataSource;
}
#Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl(getDataSource());
}
}
HomeController:
package net.codejava.spring.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.codejava.spring.dao.ContactDAO;
import net.codejava.spring.model.Contact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* This controller routes accesses to the application to the appropriate
* hanlder methods.
* #author www.codejava.net
*
*/
#Controller
public class HomeController {
#Autowired
private ContactDAO contactDAO;
#RequestMapping(value="/")
public ModelAndView listContact(ModelAndView model) throws IOException{
List<Contact> listContact = contactDAO.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
#RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contact newContact = new Contact();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute Contact contact) {
contactDAO.saveOrUpdate(contact);
return new ModelAndView("redirect:/");
}
#RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
}
#RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contact contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
}
ContactDAO:
package net.codejava.spring.dao;
import java.util.List;
import net.codejava.spring.model.Contact;
/**
* Defines DAO operations for the contact model.
* #author www.codejava.net
*
*/
public interface ContactDAO {
public void saveOrUpdate(Contact contact);
public void delete(int contactId);
public Contact get(int contactId);
public List<Contact> list();
}
ContactDAOImpl:
package net.codejava.spring.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import net.codejava.spring.model.Contact;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
/**
* An implementation of the ContactDAO interface.
* #author www.codejava.net
*
*/
public class ContactDAOImpl implements ContactDAO {
private JdbcTemplate jdbcTemplate;
public ContactDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
#Override
public void saveOrUpdate(Contact contact) {
if (contact.getId() > 0) {
// update
String sql = "UPDATE contact SET name=?, email=?, address=?, "
+ "telephone=? WHERE contact_id=?";
jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
contact.getAddress(), contact.getTelephone(), contact.getId());
} else {
// insert
String sql = "INSERT INTO contact (name, email, address, telephone)"
+ " VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
contact.getAddress(), contact.getTelephone());
}
}
#Override
public void delete(int contactId) {
String sql = "DELETE FROM contact WHERE contact_id=?";
jdbcTemplate.update(sql, contactId);
}
#Override
public List<Contact> list() {
String sql = "SELECT * FROM contact";
List<Contact> listContact = jdbcTemplate.query(sql, new RowMapper<Contact>() {
#Override
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
Contact aContact = new Contact();
aContact.setId(rs.getInt("contact_id"));
aContact.setName(rs.getString("name"));
aContact.setEmail(rs.getString("email"));
aContact.setAddress(rs.getString("address"));
aContact.setTelephone(rs.getString("telephone"));
return aContact;
}
});
return listContact;
}
#Override
public Contact get(int contactId) {
String sql = "SELECT * FROM contact WHERE contact_id=" + contactId;
return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
#Override
public Contact extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contact contact = new Contact();
contact.setId(rs.getInt("contact_id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));
contact.setAddress(rs.getString("address"));
contact.setTelephone(rs.getString("telephone"));
return contact;
}
return null;
}
});
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.codejava.spring</groupId>
<artifactId>SpringMvcJdbcTemplate</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringMvcJdbcTemplate</name>
<url>http://maven.apache.org</url>
<properties>
<java.version>1.8</java.version>
<spring.version>4.0.3.RELEASE</spring.version>
<cglib.version>2.2.2</cglib.version>
</properties>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<!-- Spring core & mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- CGLib for #Configuration -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Servlet Spec -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMvcJdbcTemplate</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
I have fixed the same error in intellij idea by switching from jdk-16 to jdk-13 in my pom.xml and in my project sdk (File --> project structure --> project --> jdk-13).
Further more i was using servlet api instead of web.xml
Try to update your project, to download all libraries and then you will see the absolute path for postgresql Driver.
Related
'm New On Spring I just Start a Spring MVC CRUD Program but I'm Facing the Same Errors Again and Again After Try many ways.
This is the First Exception Which Printing HTTP Status 500 – Internal Server Error.
HTTP Status 500 – Internal Server Error
javax.servlet.ServletException: Servlet.init() for servlet [dispatcher] threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
Unsatisfied Dependency Exception
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentDao' defined in file [C:\Users\MOHIT SINGH\Documents\workspace-spring-tool-suite-4-4.6.2.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\STUDENT-SPRING-MVC\WEB-INF\classes\com\spring\student\dao\StudentDaoImpl.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<com.spring.student.model.Student>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<com.spring.student.model.Student>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
NoSuchBeanDefinitionException
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<com.spring.student.model.Student>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:834)
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
Code
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.java.spring</groupId>
<artifactId>STUDENT-SPRING-MVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>STUDENT-SPRING-MVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>4.3.0.RELEASE</springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<mysql.version>5.1.31</mysql.version>
<joda-time.version>2.3</joda-time.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- jsr303 validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- Joda-Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<!-- To map JodaTime with database type -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.0.0.CR1</version>
</dependency>
<!-- Servlet+JSP+JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Testing dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>STUDENT-SPRING-MVC</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Configuration
package com.spring.student.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan("com.spring.student")
public class MyWebConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
ServletInitilizer
package com.spring.student.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {MyWebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
HibernateConfiguration
package com.spring.student.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.spring.student.configuration" })
#PropertySource(value = { "classpath:application.properties" })
public class MyHibernateConfig {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.spring.student.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show.sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
Dao
package com.spring.student.dao;
import java.io.Serializable;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.lang.reflect.ParameterizedType;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstStudentDao<PK extends Serializable, T> {
private final Class<T> persistentClass;
#SuppressWarnings("unchecked")
public AbstStudentDao(Class<T> persistentClass) {
super();
this.persistentClass = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[1];
}
#Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
public T getByKey(PK key) {
return (T) getSession().get(persistentClass, key);
}
public void persist(T entity) {
getSession().persist(entity);
}
public void saveOrUpdate(T entity) {
getSession().saveOrUpdate(entity);
}
public void delete(T entity) {
getSession().delete(entity);
}
protected Criteria createEntityCriteria() {
return getSession().createCriteria(persistentClass);
}
}
DaoImpl
package com.spring.student.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.spring.student.model.Student;
#Repository("studentDao")
public class StudentDaoImpl extends AbstStudentDao<Integer, Student> implements StudentDao {
public StudentDaoImpl(Class<Student> persistentClass) {
super(persistentClass);
}
public void saveOrUpdate(Student student) {
super.saveOrUpdate(student);
}
#Override
public Student findById(int id) {
return getByKey(id);
}
#Override
public void saveStudent(Student student) {
persist(student);
}
#Override
public void deleteStudentByCode(String code) {
Query query = getSession().createQuery("delete from student where code = :code");
query.setParameter("code", code);
query.executeUpdate();
}
#SuppressWarnings("unchecked")
#Override
public List<Student> findAllStudents() {
Criteria criteria = createEntityCriteria();
return (List<Student>) criteria.list();
}
#Override
public Student findStudentByCode(String code) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("code", code));
return (Student) criteria.uniqueResult();
}
}
ServiceImple
package com.spring.student.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.spring.student.dao.StudentDao;
import com.spring.student.model.Student;
#Service("studentService")
#Transactional
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
#Override
public Student findById(int Id) {
return studentDao.findById(Id);
}
#Override
public void saveStudent(Student student) {
studentDao.saveStudent(student);
}
#Override
public void updateStudent(Student student) {
Student entity = studentDao.findById(student.getId());
if (entity != null) {
entity.setName(student.getName());
entity.setEnteringDate(student.getEnteringDate());
entity.setNationality(student.getNationality());
entity.setCode(student.getCode());
}
}
#Override
public List<Student> findAllStudent() {
return studentDao.findAllStudents();
}
#Override
public Student findStudentByCode(String code) {
return studentDao.findStudentByCode(code);
}
#Override
public boolean isStudentCodeUnique(Integer id, String code) {
Student student = findStudentByCode(code);
return (student == null || ((id != null) && (student.getId() == id)));
}
#Override
public void deleteStudentByCode(String code) {
studentDao.deleteStudentByCode(code);
}
}
Controller
package com.spring.student.controller;
import java.util.Locale;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.student.model.Student;
import com.spring.student.service.StudentService;
#Controller
#RequestMapping("/")
public class MyController {
#Autowired
StudentService service;
#Autowired
MessageSource messageSource;
#RequestMapping(value = { "/new" }, method = RequestMethod.GET)
public String studentList(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
model.addAttribute("edit", false);
return "registration";
}
#RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveStudent(#Valid Student student, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
if (!service.isStudentCodeUnique(student.getId(), student.getCode())) {
FieldError codeError = new FieldError("student", "code", messageSource.getMessage("non.unique.code",
new String[] { student.getCode() }, Locale.getDefault()));
result.addError(codeError);
return "registration";
}
service.saveStudent(student);
model.addAttribute("success", "student" + student.getName() + "Registration Successfull");
return "success";
}
#RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.GET)
public String editStudent(#PathVariable String code, ModelMap model) {
Student student = service.findStudentByCode(code);
model.addAttribute("student", student);
model.addAttribute("edit", true);
return "registration";
}
#RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.POST)
public String updateStudent(#Valid Student student, BindingResult result, ModelMap model,
#PathVariable String code) {
if (result.hasErrors()) {
return "registration";
}
if (!service.isStudentCodeUnique(student.getId(), student.getCode())) {
FieldError codeError = new FieldError("student", "code", messageSource.getMessage("non.unique.code",
new String[] { student.getCode() }, Locale.getDefault()));
result.addError(codeError);
return "registration";
}
service.saveStudent(student);
model.addAttribute("success", "student" + student.getName() + "Update SuccessFully Completed");
return "success";
}
#RequestMapping(value = { "/delete-{code}-student" }, method = RequestMethod.GET)
public String deleteStudent(#PathVariable String code) {
service.deleteStudentByCode(code);
return "redirect:/list";
}
}
Did you try making Class<Student> to just Student in StudentDaoImpl constructor? Is it not allowing without Class<>?
Change constructor of StudentDaoImpl class to
public StudentDaoImpl() {
super(Student.class);
}
And autowire studentdao in StudentServiceImpl class
Hope it will work
First of all, you should autowired "StrudentDoa"
Secondly, you did not need to define service name within a bracket #Service()
package com.spring.student.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.spring.student.dao.StudentDao;
import com.spring.student.model.Student;
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDao studentDao;
#Override
public Student findById(int Id) {
return studentDao.findById(Id);
}
#Override
public void saveStudent(Student student) {
studentDao.saveStudent(student);
}
#Override
public void updateStudent(Student student) {
Student entity = studentDao.findById(student.getId());
if (entity != null) {
entity.setName(student.getName());
entity.setEnteringDate(student.getEnteringDate());
entity.setNationality(student.getNationality());
entity.setCode(student.getCode());
}
}
#Override
public List<Student> findAllStudent() {
return studentDao.findAllStudents();
}
#Override
public Student findStudentByCode(String code) {
return studentDao.findStudentByCode(code);
}
#Override
public boolean isStudentCodeUnique(Integer id, String code) {
Student student = findStudentByCode(code);
return (student == null || ((id != null) && (student.getId() == id)));
}
#Override
public void deleteStudentByCode(String code) {
studentDao.deleteStudentByCode(code);
}
}
Try with #Transactional annotation in ur daoImpl class
While i am building this code i am getting error bean is not creating for DAO class even though annotations are added correctly
WARNING: Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bankDaoImpl'
defined in file [C:\Users\saivi\eclipse-
workspace\bank\target\classes\com\bank\dao\BankDaoImpl.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.bank.dao.BankDaoImpl]: Constructor threw exception; nested exception is
java.lang.NullPointerException
Nov 28, 2019 9:50:45 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bankDaoImpl'
defined in file [C:\Users\saivi\eclipse-
workspace\bank\target\classes\com\bank\dao\BankDaoImpl.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.bank.dao.BankDaoImpl]: Constructor threw exception; nested exception is
java.lang.NullPointerException
AppConfig.java
package com.bank.config;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import static org.hibernate.cfg.Environment.*;
#Configuration
#PropertySource("classpath:db.properties")
#EnableTransactionManagement
#ComponentScans(value = { #ComponentScan("com.bank.dao"),
#ComponentScan("com.bank.service") })
public class AppConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
Properties props = new Properties();
// Setting JDBC properties
props.put(DRIVER, env.getProperty("mysql.driver"));
props.put(URL, env.getProperty("mysql.url"));
props.put(USER, env.getProperty("mysql.user"));
props.put(PASS, env.getProperty("mysql.password"));
// Setting Hibernate properties
props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
// Setting C3P0 properties
props.put(C3P0_MIN_SIZE, env.getProperty("hibernate.c3p0.min_size"));
props.put(C3P0_MAX_SIZE, env.getProperty("hibernate.c3p0.max_size"));
props.put(C3P0_ACQUIRE_INCREMENT,
env.getProperty("hibernate.c3p0.acquire_increment"));
props.put(C3P0_TIMEOUT, env.getProperty("hibernate.c3p0.timeout"));
props.put(C3P0_MAX_STATEMENTS, env.getProperty("hibernate.c3p0.max_statements"));
factoryBean.setHibernateProperties(props);
factoryBean.setPackagesToScan("com.bank.model");
return factoryBean;
}
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
}
MyWebAppInitializer.java
package com.bank.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {AppConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
WebConfig.java
package com.bank.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages= {"com.bank.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
}
Bank.java
package com.bank.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="Bank")
public class Bank {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
private Integer balance;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
}
BankDaoImpl.java
package com.bank.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.bank.model.Bank;
#Repository
public class BankDaoImpl implements BankDao{
#Autowired
private SessionFactory sessionFactory;
Session s=sessionFactory.getCurrentSession();
#Override
public long save(Bank bank) {
s.save(bank);
return bank.getId();
}
#Override
public Bank get(long id) {
return s.get(Bank.class, id);
}
#Override
public void delete(long id) {
Bank b=s.byId(Bank.class).load(id);
s.delete(b);
}
}
BankService.java
package com.bank.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bank.dao.BankDao;
import com.bank.model.Bank;
#Service
#Transactional(readOnly=true)
public class BankServiceImpl implements BankService {
#Autowired
private BankDao bankDao;
#Transactional
#Override
public long save(Bank bank) {
return bankDao.save(bank);
}
#Override
public Bank get(long id) {
return bankDao.get(id);
}
#Override
public void delete(long id) {
bankDao.delete(id);
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bank</groupId>
<artifactId>bank</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- Hibernate-C3P0 Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- Jackson API for JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Embedded Apache Tomcat required for testing web application -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
The following line in your code sampleSession s=sessionFactory.getCurrentSession(); in BankDaoImpl will cause a NullPointerException, because the SessionFactory object hasn't been Autowired yet and you are already trying to invoke its methods.
Try to replace the line into each of the methods within that class. So for example, your BankDaoImpl#save method will look like this:
public class BankDaoImpl {
#Autowired
SessionFactory sessionFactory;
#Override
public long save(Bank bank) {
Session s = sessionFactory.getCurrentSession();
s.save(bank);
return bank.getId();
}
...
}
Try to do the above for every other method that uses sessionFactory in the BankDaoImplclass.
I have just started springboot and tried to implement elastic search with spring-boot but I am getting this type of error while running spring-boot app
Consider defining a bean named 'elasticsearchTemplate' in your configuration.
POM.XML
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
Repository
#Repository
public interface StudentRepository extends ElasticsearchRepository<Student, Integer>{}
Controller
#RestController
public class Controller {
#Autowired
StudentRepository studentRepo;
#GetMapping(value="/student/all")
List<Student> getAllStudent() {
Iterator<Student> studentList = studentRepo.findAll().iterator();
List<Student> students = new ArrayList<>();
if(studentList.hasNext()) {
students.add(studentList.next());
}
return students;
}
#PostMapping(value="/student/add")
String addStudent(#RequestBody Student student) {
studentRepo.save(student);
return "Record Added Successfully";
}
#DeleteMapping(value="/student/delete/{id}")
String deleteStudent(#PathVariable int id) {
studentRepo.deleteById(id);
return "Record Deleted Successfully";
}
//#GetMapping(value="/student/findById/{id}")
}
Can Anyone help me to resolve this error
Consider defining a bean named 'elasticsearchTemplate' in your configuration.
You need to define some elastic search properties in your application.properties file such as cluster-nodes, cluster-names which are used by ElasticsearchTemplate and ElasticsearchRepository to connect to the Elasticsearch engine.
You can refer below mentioned link :
https://dzone.com/articles/elasticsearch-with-spring-boot-application
Note: Please refer to the spring-data-elasticsearch-versions or Spring Data Elasticsearch Changelog (check Elasticsearch version of desired release) to check version compatibility.
Solution(1):
If you want to use spring boot 1.x, simply create a #Configuration class and add a ElasticsearchOperations Bean. Please note than spring boot 1.x does not support the latest versions of ElasticSearch 5.x and higher.
cluster.name: make sure the cluster name you set in the code is the same as the cluster.name you set in $ES_HOME/config/elasticsearch.yml
#Configuration
public class ElasticSearchConfig {
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(getClient());
}
#Bean
public Client getClient() throws UnknownHostException {
Settings setting = Settings
.builder()
.put("client.transport.sniff", true)
.put("path.home", "/usr/share/elasticsearch") //elasticsearch home path
.put("cluster.name", "elasticsearch")
.build();
//please note that client port here is 9300 not 9200!
TransportClient client = new PreBuiltTransportClient(setting)
.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
return client;
}
}
Solution (2):Also, you can refer to this spring boot issue that shows automatic configuration of the Elasticsearch in the spring data from spring boot 2.2.0.
Therefore, using spring boot 2.2 and spring-boot-starter-elasticserach you don't need to configure the Elasticsearch manually.
Sample working project:
Versions:
spring boot : 2.2.0.RELEASE
Elasticsearch: 6.6.2
Pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-boot-elasticsearch</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.properties:
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.elasticsearch.jest.uris=http://localhost:9200
Main Application class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Model class:
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
#Document(indexName = "your_index", type = "books")
public class Book {
#Id
private String id;
private String title;
private String author;
private String releaseDate;
//getter, setter/constructors
}
Repository class:
import com.example.model.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
Page<Book> findByAuthor(String author, Pageable pageable);
List<Book> findByTitle(String title);
}
Service class:
some methods to test:
import com.example.model.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
public interface BookService {
Book save(Book book);
void delete(Book book);
Book findOne(String id);
Iterable<Book> findAll();
Page<Book> findByAuthor(String author, Pageable pageable);
List<Book> findByTitle(String title);
}
Service implementation:
import com.example.model.Book;
import com.example.repository.BookRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class BookServiceImpl implements BookService {
private BookRepository bookRepository;
public BookServiceImpl(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
#Override
public Book save(Book book) {
return bookRepository.save(book);
}
#Override
public void delete(Book book) {
bookRepository.delete(book);
}
#Override
public Book findOne(String id) {
return bookRepository.findById(id).orElse(null);
}
#Override
public Iterable<Book> findAll() {
return bookRepository.findAll();
}
#Override
public Page<Book> findByAuthor(String author, Pageable pageable) {
return bookRepository.findByAuthor(author, pageable);
}
#Override
public List<Book> findByTitle(String title) {
return bookRepository.findByTitle(title);
}
}
Test class:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = Application.class)
public class BookTest {
#Autowired
private BookService bookService;
#Autowired
private ElasticsearchTemplate esTemplate;
#Before
public void before(){
esTemplate.deleteIndex(Book.class);
esTemplate.createIndex(Book.class);
esTemplate.putMapping(Book.class);
esTemplate.refresh(Book.class);
}
#Test
public void testSave(){
Book book = new Book("1001", "Elasticsearch", "title", "23-FEB-2017");
Book testBook = bookService.save(book);
assertNotNull(testBook.getId());
assertEquals(testBook.getTitle(), book.getTitle());
assertEquals(testBook.getAuthor(), book.getAuthor());
assertEquals(testBook.getReleaseDate(), book.getReleaseDate());
}
}
I am learning from book Spring In Action 4. I have problem in chapter 5. I cant run this example with spring boot and maven.
I get following mesage:
Consider defining a bean of type 'spittr.data.SpitterRepository' in your configuration.
I have this bean but componentScan doeasnt see it.
Here is whole code:
https://github.com/Kobooo/SpringInAction4Spitter
Aplication files
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.howtodoinjava</groupId>
<artifactId>spring-boot-demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Tomcat Embed -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- Equals -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<!-- TESTS -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.8.47</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
SpitterController.java
package spittr.web;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import spittr.Spitter;
import spittr.data.SpitterRepository;
#Controller
#RequestMapping("/spitter")
public class SpitterController {
private SpitterRepository spitterRepository;
#Autowired
public SpitterController(SpitterRepository spitterRepository) {
this.spitterRepository = spitterRepository;
}
#RequestMapping(value="/register", method=GET)
public String showRegistrationForm() {
return "registerForm";
}
#RequestMapping(value="/register", method=POST)
public String processRegistration(
#Valid Spitter spitter,
Errors errors) {
if (errors.hasErrors()) {
return "registerForm";
}
spitterRepository.save(spitter);
return "redirect:/spitter/" + spitter.getUsername();
}
#RequestMapping(value="/{username}", method=GET)
public String showSpitterProfile(#PathVariable String username, Model model) {
Spitter spitter = spitterRepository.findByUsername(username);
model.addAttribute(spitter);
return "profile";
}
}
JdbcSpitterRepository.java
package spittr.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import spittr.Spitter;
#Repository
public class JdbcSpitterRepository implements SpitterRepository {
private JdbcOperations jdbc;
#Autowired
public JdbcSpitterRepository(JdbcOperations jdbc) {
this.jdbc = jdbc;
}
public Spitter save(Spitter spitter) {
jdbc.update(
"insert into Spitter (username, password, first_name, last_name, email)" +
" values (?, ?, ?, ?, ?)",
spitter.getUsername(),
spitter.getPassword(),
spitter.getFirstName(),
spitter.getLastName(),
spitter.getEmail());
return spitter; // TODO: Determine value for id
}
public Spitter findByUsername(String username) {
return jdbc.queryForObject(
"select id, username, null, first_name, last_name, email from Spitter where username=?",
new SpitterRowMapper(),
username);
}
private static class SpitterRowMapper implements RowMapper<Spitter> {
public Spitter mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Spitter(
rs.getLong("id"),
rs.getString("username"),
null,
rs.getString("first_name"),
rs.getString("last_name"),
rs.getString("email"));
}
}
}
SpringBootWebApplication.java
package spittr.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
#SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootWebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(new Class[] {SpringBootWebApplication.class} ,args);
}
}
WebConfig.java
package spittr.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
#Import(spittr.config.DataConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
super.addResourceHandlers(registry);
}
}
DataConfig.java
package spittr.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
#Configuration
public class DataConfig {
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
}
#Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
SpitterWebInitializer
package spittr.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import spittr.web.WebConfig;
#Configuration
public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
root
package spittr.config;
import java.util.regex.Pattern;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
import spittr.config.RootConfig.WebPackage;
import spittr.web.WebConfig;
#Configuration
#ComponentScan(basePackages={"spittr"},
excludeFilters={
#Filter(type=FilterType.CUSTOM, value=WebPackage.class)
})
public class RootConfig {
public static class WebPackage extends RegexPatternTypeFilter {
public WebPackage() {
super(Pattern.compile("spittr\\.web"));
}
}
}
I'm pretty new to Java, but I wanted to try to build a simple project with SpringMVC. It's just a simple CRUD app that should allow people to post notes.
When attempting to submit the form or query for notes, I get a null pointer exception when I attempt to call methods on JdbcTemplate. Here is the code for my application class:
package mvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
#SpringBootApplication
public class SpringMvcApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringMvcApplication.class, args);
}
#Autowired
JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void run(String... string) throws Exception {
System.out.println("Creating tables");
jdbcTemplate.execute("drop table notes if exists");
jdbcTemplate.execute(("create table notes(" +
"id serial, content varchar(255), author varchar(255))"));
}
public static SpringMvcApplication instance = new SpringMvcApplication();
public static SpringMvcApplication getInstance() { return instance; }
}
Here is my NoteController.java:
package mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class NoteController {
#RequestMapping("/notes")
public String index() {
return "index";
}
#RequestMapping("/notes/new")
public String newNote(Model model) {
model.addAttribute("note",new Note());
return "new";
}
#RequestMapping(value="/notes", method= RequestMethod.POST)
public String create(Note note, Model model) {
model.addAttribute("note", note);
Note.create(note.getContent(), note.getAuthor());
return "show";
}
#RequestMapping(value = "/notes/{noteId}", method=RequestMethod.GET)
public String show(#PathVariable String noteId) {
long id = Long.parseLong(noteId);
Note note = Note.find(id);
return "show";
}
}
My Note model:
package mvc;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class Note {
private Long id;
private String content;
private String author;
public Note() {}
public Note(Long id, String content, String author) {
this.id = id;
this.content = content;
this.author = author;
}
public Long getId() {
return id;
}
public String getContent() {
return content;
}
public String getAuthor() {
return author;
}
public String toString() {
return content + "by " + author;
}
public static void create(String content, String author) {
JdbcTemplate jdbcTemplate = SpringMvcApplication.getInstance().getJdbcTemplate();
jdbcTemplate.update("INSERT INTO notes(content, author) values (?,?)", content, author);
}
public static Note find(Long id) {
JdbcTemplate jdbcTemplate = SpringMvcApplication.getInstance().getJdbcTemplate();
List<Note> notes = jdbcTemplate.query("SELECT id, content, author FROM notes WHERE id = ?", new Object[]{id},
new RowMapper<Note>() {
#Override
public Note mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Note(rs.getLong("id"), rs.getString("content"),
rs.getString("author"));
}
});
return notes.get(0);
}
}
Here's my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring MVC</name>
<description>MVC Project for Ship It Saturday</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>mvc.SpringMvcApplication</start-class>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.4</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
I'm not really sure what the issue is with my code here. I was following a few different guides but most of them weren't too clear on what code was doing what. I'm sure there are probably some really obvious issues here, but I'm totally new to Spring and Java so I'm not seeing it.
EDIT:
Here is what I think are the relevant lines of the trace:
2015-04-11 19:01:35.125 ERROR 24895 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at mvc.Note.create(Note.java:44)
at mvc.NoteController.create(NoteController.java:30)
I should also mention that the run() method in the SpringMVCApplication class works just fine at creating the table, and if I move the insert and query statements into that method with static data the also work. It's only when I move them into their own methods so that I can use them dynamically that everything falls apart.
As already mentioned in the comments your SpringMvcApplication.getInstance() will not work as expected. You need something to connect the "spring-world" with the "not-spring-world". A possible solution would be to save the ApplicationContext as singleton.
#SpringBootApplication
public class SpringMvcApplication {
private static ApplicationContext context;
public static void main(String[] args) {
context = SpringApplication.run(SpringMvcApplication.class, args);
}
public static JdbcTemplate getJdbcTemplate() {
return context.getBean(JdbcTemplate.class);
}
}
Maybe you have to adapt it to your needs.