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.
Related
I started with a simple project using spring jpa and a simple maven class just to test this basic behavior. Everything worked fine. My next step was to divide this single project into two projects in order to have a persistence project responsible for data access and another one to be enriched with business logic. This is where everything breaks. The proof that this is related to java modules is that If I delete module-info.java on both projects everything works fine.
If I simply run the application I get
Exception in thread "main" java.lang.NoClassDefFoundError: java/lang/instrument/IllegalClassFormatException
at spring.data.jpa#2.7.3/org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.getConfigurationInspectionClassLoader(JpaRepositoryConfigExtension.java:239)
at spring.data.commons#2.7.3/org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport.getRepositoryConfigurations(RepositoryConfigurationExtensionSupport.java:97)
at spring.data.commons#2.7.3/org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:159)
at spring.data.commons#2.7.3/org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:106)
at spring.context#5.3.23/org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:396)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at spring.context#5.3.23/org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:395)
at spring.context#5.3.23/org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:157)
at spring.context#5.3.23/org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:129)
at spring.context#5.3.23/org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:343)
at spring.context#5.3.23/org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:247)
at spring.context#5.3.23/org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:311)
at spring.context#5.3.23/org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:112)
at spring.context#5.3.23/org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:746)
at spring.context#5.3.23/org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:564)
at spring.context#5.3.23/org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)
at test/org.test.Main.main(Main.java:15)
Caused by: java.lang.ClassNotFoundException: java.lang.instrument.IllegalClassFormatException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 17 more
If I debug it, it starts complaining about missing classes (Derby, hibernate, etc).
All this leads me to believe that the problem is on java module declaration, but I don't know how can I solve this..
This is my file structure:
- test
-- src.main.java
--- org.test
---- Config.java
---- Main.java
--- module-info.java
--- src.main.resources
---- org/test/application.properties
-- pom.xml
- test-persistence
-- src.main.java
--- org.test.persistence
---- CustomRepository.java
---- CustomRepositoryImpl.java
---- Entity.java
---- MyRepository.java
---- PersistenceConfiguration.java
--- module-info.java
-- pom.xml
And here are the files:
test 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring.version>5.3.23</spring.version>
<spring-data.version>2.7.3</spring-data.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>test</groupId>
<artifactId>test-persistence</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
</dependencies>
</project>
test module-info:
module test {
requires testPersistence;
requires spring.context;
requires spring.beans;
requires spring.core;
requires spring.instrument;
opens org.test;
}
Config.java:
package org.test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.test.persistence.PersistenceConfiguration;
#Configuration
#ComponentScan(basePackages = "org.test")
#Import(PersistenceConfiguration.class)
public class Config {
}
Main.java
package org.test;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.test.persistence.Entity;
import org.test.persistence.MyRepository;
public class Main {
public static void main(String[] args) {
System.out.println("Running java " + Runtime.version().feature());
AnnotationConfigApplicationContext appCtx = new AnnotationConfigApplicationContext(Config.class);
MyRepository repo = appCtx.getBean(MyRepository.class);
List<Entity> result = repo.findOrderedByLastUsedLimitedTo(2);
}
}
application.properties:
spring.jpa.generate-ddl=true
spring.jpa.defer-datasource-initialization=true
spring.jpa.database-platform=org.hibernate.dialect.DerbyDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=org.apache.derby.iapi.jdbc.AutoloadedDriver
spring.datasource.url=jdbc:derby:eTimer;create=true
test-persistence 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test-persistence</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring.version>5.3.23</spring.version>
<spring-data.version>2.7.3</spring-data.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
test-persistence module-info.java:
module testPersistence {
requires java.persistence;
requires java.sql;
requires spring.data.commons;
requires spring.data.jpa;
requires spring.orm;
requires spring.jdbc;
requires spring.tx;
requires spring.context;
opens org.test.persistence;
exports org.test.persistence to test;
}
CustomRepository.java:
package org.test.persistence;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public interface CustomRepository {
List<Entity> findOrderedByDescriptionLimitedTo(int maxItems);
}
CustomRepositoryImpl.java:
package org.test.persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class CustomRepositoryImpl implements CustomRepository {
#PersistenceContext
private EntityManager entityManager;
#Override
public List<Entity> findOrderedByDescriptionLimitedTo(int limit) {
return entityManager.createQuery("SELECT p FROM Entity p ORDER BY p.description", Entity.class)
.setMaxResults(limit).getResultList();
}
}
Entity.java:
package org.test.persistence;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#javax.persistence.Entity
#Table(name = "Entity")
public class Entity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private String description;
public Entity() {
super();
}
public Entity(Long id, String description) {
super();
this.id = id;
this.description = description;
}
}
MyRepository.java:
package org.test.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface MyRepository extends JpaRepository<Entity, Long>, CustomRepository {
Entity save(Entity task);
}
PersistenceConfiguration.java:
package org.test.persistence;
import java.io.File;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#EnableJpaRepositories("org.test.persistence")
#PropertySource("org/test/application.properties")
public class PersistenceConfiguration {
private static final String DRIVER_CLASS_NAME = "org.apache.derby.iapi.jdbc.AutoloadedDriver";
private static final String DATA_SOURCE_DRIVER_URL = "jdbc:derby:test;create=true";
private static final String DATA_SOURCE_USER = null;
private static final String DATA_SOURCE_PASSWORD = null;
#Bean("entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
System.setProperty("derby.system.home", System.getProperty("user.home") + File.separatorChar + "test");
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPackagesToScan("org.test");
entityManagerFactoryBean.setPersistenceUnitName("system");
entityManagerFactoryBean.setDataSource(systemDataSource());
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.DERBY);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
entityManagerFactoryBean.setJpaVendorAdapter(adapter);
return entityManagerFactoryBean;
}
#Bean
DataSource systemDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DRIVER_CLASS_NAME);
dataSource.setUrl(DATA_SOURCE_DRIVER_URL);
dataSource.setUsername(DATA_SOURCE_USER);
dataSource.setPassword(DATA_SOURCE_PASSWORD);
return dataSource;
}
#Bean(name="transactionManager")
public PlatformTransactionManager systemTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory((entityManagerFactory().getObject()));
return transactionManager;
}
}
help please?
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 starting in Spring MVC with the Book Spring in Action, I'm making the exercise of the chapter 5, with the Spitter application but I got the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'spittleController' defined in file [C:\xampp\htdocs.metadata.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\spitter\WEB-INF\classes\com\spitter\web\SpittleController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.spitter.data.SpittleRepository]: : No qualifying bean of type [com.spitter.data.SpittleRepository] found for dependency: 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 [com.spitter.data.SpittleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
I got the project here in github: https://github.com/kevingcfcb88/spitter.git
I already do my research but nothing seems to work.
I'm using STS and Maven, this is the structure of the app:
Here is my 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>com.spitter.config</groupId>
<artifactId>spitter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spitter</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>4.1.5.RELEASE</springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<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>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>spitter</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>spitter</finalName>
</build>
And my config files:
SpittrWebAppInitializer.java
package com.spitter.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer 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[] { "/" };
}
}
WebConfig.java
package com.spitter.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.spitter.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
RootConfig.java
package com.spitter.config;
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.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages = { "com.spitter.data" }, excludeFilters = {#Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig {
}
As #mh-dev explained, you need an implementation of SpittleRepository. Try adding this class and see if your code can run:
public class SpittleRepositoryImpl implements SpittleRepository {
List <Spittle> findSpittles(long max, int count) {
System.out.println("I need a real implementation! "
+ "I received max as " + max + " and count as " + count + ".");
}
}
I would suggest re-reading the relevant sections of the book to make sure you didn't miss anything.
You just need to add a repository implementation of SpittleRepository with #Repository in the header, because even though you have added implementation classes, spring IOC is unaware of actual dependency and the example in the book should have worked if you had put all the java files in the same package hierarchy with repository implementation.
#Repository
public class SpittleRepositoryDAO implements SpittleRepository {
public SpittleRepositoryDAO() {
}
#Override
public List<Spittle> findSpittles(long max, int count) {
List<Spittle> spittles = new ArrayList<Spittle>();
for (int i = 0; i < count; i++) {
spittles.add(new Spittle("Spittle " + i, new Date()));
}
return spittles;
}
}
I know this code. It used to give me serious headache 2 years ago.
The eror is in the code OR the book itslef.
Go to the publishers site and download the updated sourcecode. here
or
https://www.manning.com/books/spring-in-action-fourth-edition
Here is the implementation of the repository:
package com.spitter.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spitter.data.SpittleRepository;
#Controller
#RequestMapping("/spittles")
public class SpittleController {
private SpittleRepository spittleRepository;
#Autowired
public SpittleController(SpittleRepository spittleRepository) {
this.spittleRepository = spittleRepository;
}
#RequestMapping(method = RequestMethod.GET)
public String spittles(Model model) {
model.addAttribute("spittleList", spittleRepository.findSpittles(Long.MAX_VALUE, 20));
return "spittles";
}
}
yep, the problem is that you need an implementation of SpittleRepository. Cause you can't have an interface as bean, you know. The scan component need at least one implementation of it and with the annotation #Component. That's it ;)
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.