Why does Spring throw "IllegalStateException: No ServletContext set" when using a WebApplicationInitializer - java

im just learning java, and now try to creat UI for my application with using MVC+thymeleaf. When i try to run application, i get error, stacktrace like this:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)
at com.foxminded.university.Main.main(Main.java:26)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
... 14 more
Caused by: java.lang.IllegalStateException: No ServletContext set
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:534)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 15 more
my config file:
#Configuration
#ComponentScan("com.foxminded.university")
#PropertySource("classpath:config.properties")
#EnableWebMvc
public class ContextConfig implements WebMvcConfigurer {
private final ApplicationContext applicationContext;
#Value("${url}")
public String url;
#Value("${user}")
public String user;
#Value("${password}")
public String password;
#Value("${driverClass}")
public Class<Driver> driverClass;
#Autowired
public ContextConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean
public DataSource dataSource() {
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriverClass(driverClass);
dataSource.setUsername(user);
dataSource.setUrl(url);
dataSource.setPassword(password);
return dataSource;
}
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
registry.viewResolver(resolver);
}
}
dispatcherServlet:
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ContextConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
and 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>com.foxminded.tasks</groupId>
<artifactId>University1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>University1</name>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<junit.jupiter.version>5.6.0</junit.jupiter.version>
<org.springframework.version>5.2.5.RELEASE</org.springframework.version>
<org.springframework.boot.version>2.2.6.RELEASE</org.springframework.boot.version>
<h2.version>1.4.200</h2.version>
<org.postgres.version>42.2.11</org.postgres.version>
<org.sonarsource.scanner.maven.version>3.2</org.sonarsource.scanner.maven.version>
<mockito.version>3.3.3</mockito.version>
<logback.version>1.3.0-alpha5</logback.version>
<slf4j.version>2.0.0-alpha1</slf4j.version>
<servlet.version>4.0.1</servlet.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
</properties>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.host.url>
http://localhost:9000
</sonar.host.url>
</properties>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<version>${org.springframework.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>${org.sonarsource.scanner.maven.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${org.postgres.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
</project>
please, can u explain, where is problem and what can i do. I tried to delete .m2 repository and rebuild project, but nothing was happend.
main method i didn change from creating dao and service layer, its make little menu in console for getting time table for students and teachers:
public class Main {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
logger.info("Start Main");
#SuppressWarnings("resource")
final ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfig.class);
DatabaseInitializer initializer = context.getBean("databaseInitializer", DatabaseInitializer.class);
try {
initializer.createTableInsertData();
} catch (IOException e1) {
logger.error("DB was not created");
System.exit(0);
}
TimeTable timeTable = context.getBean("timeTable", TimeTable.class);
TeacherService teacherService = context.getBean("teacherService", TeacherService.class);
StudentService studentService = context.getBean("studentService", StudentService.class);
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
final String commandListMessage = "Please select which TimeTable you want take:\n"
+ "\"1\" - TimeTable for student for selected interval;\n"
+ "\"2\" - TimeTable for teacher for selected interval;\n"
+ "\"help\" - for get this list of commands again;\n" + "or \"exit\" to exit.";
System.out.println(commandListMessage);
String command = "";
try {
command = reader.readLine();
logger.debug("command is {}", command);
logger.debug("start menu loop");
while (!(command.equalsIgnoreCase("exit"))) {
logger.info("switch command");
switch (command) {
case "1":
logger.debug("case 1");
System.out.println("Enter student id:");
int studentId = Integer.parseInt(reader.readLine());
Student student = studentService.findOne(studentId);
if (student != null) {
System.out.println("Enter date interval as \"MM.DD-MM.DD\":");
String[] dateInterval = reader.readLine().split("\\D");
logger.debug("getting TT for student {} and period {}.{}-{}.{}", student, dateInterval[0], dateInterval[1], dateInterval[2], dateInterval[3]);
String timeTableString = timeTable.getTTForGroup(student,
LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[0])),
Integer.parseInt(dateInterval[1]), 0, 0, 0),
LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[2])),
Integer.parseInt(dateInterval[3]), 23, 59, 59));
timeTable.printTimeTable(timeTableString);
} else {
System.out.println("student whith this id \"" + studentId + "\" is not exist.");
logger.warn("student with this id {} is not exist", studentId);
}
break;
case "2":
logger.debug("case 2");
System.out.println("Enter teacher id:");
int teacherId = Integer.parseInt(reader.readLine());
Teacher teacher = teacherService.findOne(teacherId);
if (teacher != null) {
System.out.println("Enter date interval as \"MM.DD-MM.DD\":");
String[] dateInterval = reader.readLine().split("\\D");
logger.debug("getting TT for teacher {} and period {}.{}-{}.{}", teacher, dateInterval[0], dateInterval[1], dateInterval[2], dateInterval[3]);
String timeTableString = timeTable.getTTForTeacher(teacher,
LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[0])),
Integer.parseInt(dateInterval[1]), 0, 0, 0),
LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[2])),
Integer.parseInt(dateInterval[3]), 23, 59, 59));
timeTable.printTimeTable(timeTableString);
} else {
System.out.println("teacher whith this id \"" + teacherId + "\" is not exist.");
logger.warn("teacher with this id {} is not exist", teacherId);
}
break;
case "help":
logger.debug("case help");
System.out.println(commandListMessage);
break;
default:
logger.debug("case default");
System.out.println("Please enter the correct command.");
break;
}
command = reader.readLine();
}
reader.close();
} catch (IOException e) {
logger.error("Reading failure", e);
}
logger.info("Exit Main");
}
}

As was said, the problem was with tomcat. i added tomcat7 plugin and maven-war-plugin, and run it as tomcat7:run, so it works now. and make version of servlet 4.0.0, not 4.0.1 cause for some reason it does not work with it.

I guess you may not have overridden methods of this class
AbstractAnnotationConfigDispatcherServletInitializer correctly. Look something around this. Enable debug log. Why don't you give try with Spring Boot. It automatically manages creation of all dependencies for you.

Related

Primefaces Spring boot - authentication provider is called twice

I am building an application with spring boot(war) and primefaces. I created a login with a custom authentication provider. When my app is processing the credentials, spring verify them twice. Why?
ColombianApplication.java
#Configuration
#EnableJpaRepositories("com.colombian.online.repository")
#EntityScan("com.colombian.online.entity")
#ComponentScan("com.colombian.online")
#SpringBootApplication
public class ColombianApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ColombianApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ColombianApplication.class);
}
}
CustomAutheticationProvider.java
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Autowired
private LoginService loginService;
#Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
Usuario usuario = getCurrentUser();
if (usuario == null) {
String username = auth.getName();
String password = auth.getCredentials().toString();
Usuario usuarioQuery = loginService.findUserByCredentials(username, password);
if (usuarioQuery == null) {
throw new UsernameNotFoundException("User not exist or your credentials are incorrect");
}
return new UsernamePasswordAuthenticationToken(usuarioQuery, password);
}
return new UsernamePasswordAuthenticationToken(usuario
, usuario.getPwd());
}
#Override
public boolean supports(Class<?> type) {
return type.equals(UsernamePasswordAuthenticationToken.class);
}
public Usuario getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof String) {
return null;
}
return (Usuario) principal;
} else {
return null;
}
}
}
CustomContextInitializer.java
#Configuration
public class CustomContextInitializer {
#Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> {
servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
servletContext.setInitParameter("primefaces.THEME", "nova-light");
};
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean<>(new FacesServlet(), "*.xhtml");
registration.setName("Faces Servlet");
registration.setLoadOnStartup(1);
return registration;
}
#Bean
public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
return new ServletListenerRegistrationBean<>(new ConfigureListener());
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/resources/**", "/javax.faces.resource/**", "/"
).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/").failureUrl("/?error=true")
.defaultSuccessUrl("/home")
.and()
.logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/");
}
#Bean
public FilterRegistrationBean rewriteFilter() {
FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST,
DispatcherType.ASYNC, DispatcherType.ERROR));
rwFilter.addUrlPatterns("/*");
return rwFilter;
}
}
My pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Primefaces with spring -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>7.0</version>
</dependency>
<!--dependency>
<groupId>org.joinfaces</groupId>
<artifactId>joinfaces-dependencies</artifactId>
<version>4.1.1</version>
<type>pom</type>
</dependency-->
<!-- Pretty faces -->
<dependency>
<groupId>org.ocpsoft.rewrite</groupId>
<artifactId>rewrite-servlet</artifactId>
<version>3.4.4.Final</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- Loggers -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- Spring tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.1-b04</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.1-b04</version>
<type>jar</type>
</dependency>
</dependencies>
The project has not web.xml. I use ocp library.
I fixed the problem, verifying the current user from SecurityContextHolder, and sending the same credentials.

Error creating bean with name 'entityManagerFactory'. What problem it can be?

I try to create Spring data jpa program without SpringBoot.
Configuration class:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"springdata.repository"})
#ComponentScan(basePackages = {"springdata.entities.service"})
#PropertySource("classpath:data.properties")
public class SpringDataConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
final BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(env.getProperty("jdbc.url"));
basicDataSource.setUsername(env.getProperty("jdbc.user"));
basicDataSource.setPassword(env.getProperty("jdbc.password"));
return basicDataSource;
}
#Bean
public Properties hibernateProperties() {
final Properties hibernateProp = new Properties();
hibernateProp.put("hibernate.dialect", "org.hibernate.H2Dialect");
hibernateProp.put("hibernate.format_sql", true);
hibernateProp.put("hibernate.use_sql_comments", true);
hibernateProp.put("hibernate.show_sql", true);
hibernateProp.put("hibernate.hbm2ddl.auto", "update");
hibernateProp.put("hibernate.max_fetch_depth", 3);
hibernateProp.put("hibernate.jdbc.batch_size", 10);
hibernateProp.put("hibernate.jdbc.fetch_size", 50);
return hibernateProp;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(final JpaVendorAdapter jpaVendorAdapter,
final Properties hibernateProperties,
final DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPackagesToScan("springdata.entities");
em.setDataSource(dataSource);
em.setJpaVendorAdapter(jpaVendorAdapter);
em.setJpaProperties(hibernateProperties);
em.afterPropertiesSet();
return em;
}
}
Test class:
public class Test {
public static void main(final String[] args) throws SQLException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringDataConfig.class);
DuckService duckService = ctx.getBean(DuckService.class);
System.out.println(duckService.findAll().size());
}
}
maven dependency:
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.1.0.Alpha2</version>
</dependency>
</dependencies>
And there are exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in springdata.SpringDataConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
I try to find decision of this proplem, and on SO was similar question, and solution was to replace javax.persistance on hibernate.javax.persistance. But in my case, I have new exception.
Change hibernate dialect
hibernateProp.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");

spring-repository save doesn't work when add spring-batch dependency?

There is application on spring4+jpa deploied on websphere 8.5.5.13
There is JPA saving in database.
So, after I added spring-batch -I faced with problem, jpa entities doesn't save.
So, the reason in transaction manager configuration like here, if I add transaction manager - JPA try to use it too.
I have root config like
#Configuration
#EnableWebMvc
#EnableBatchProcessing
#ComponentScan(basePackages = {"config"})
#PropertySource("classpath:application.properties")
public class WebAppInitalizer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(
WebConfig.class,
ServiceConfig.class,
PersistenceConfig.class,
BatchConfig.class
);
....
}
For just save entity I use spring-controller and spring repositoty. Code for saving is
record = new UserRecord(name, surname, age, updateDateTime, serialize(UserToSave));
entity:
#Entity
#Audited
#Table(name = "UserRecord")
#NoArgsConstructor(access = AccessLevel.PUBLIC)
#AllArgsConstructor
#Getter
#Setter
#Access(AccessType.FIELD)
public class UserRecord {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column(name = "PR_KEY")
private String prKey;
//Business Key
#Column(name = "name", length = 100, unique = false)
private String name;
//Business Key
#Column(name = "surname", length = 100, nullable = false)
private String surname;
//Business Key
#Column(name = "age", length = 100, nullable = false)
private int age;
#Column(name = "updateDateTime", length = 50, nullable = false)
private Timestamp updateDateTime;
#Version
private int version;
#Column(name = "user", length = 100000)
#Lob
private byte[] user;
public UserRecord(String name, String surname, String age, Timestamp updateDateTime, byte[] user) {
this.name = name;
this.surname = surname;
this.age = age;
this.updateDateTime = updateDateTime;
this.user = user;
}
}
Spring-repository:
#Repository
public interface UserRepository extends CrudRepository<UserRecord, String>
{}
When I added BatchConfig and some bean into, doesn't saving occours..
#Configuration
#EnableBatchProcessing
#Import(PersistenceConfig.class)
public class BatchConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public Job processJob() {
return jobBuilderFactory
.get("processJob")
.incrementer(new RunIdIncrementer())
.listener(listener())
.flow(step1())
.end()
.build();
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1").<Person, Person>chunk(1)
.reader(reader())
.processor(processor())
.writer(writer())
.build();
}
#Bean
public JobExecutionListener listener() {
return new JobCompletionListener();
}
#Bean
public ItemProcessor<Person, Person> processor(){
return new ItemProcessor<Person, Person>(){
#Override
public Person process(Person person) throws Exception {
person.setName(person.getName().toUpperCase());
person.setSurname(person.getSurname().toUpperCase());
person.setAge(person.getAge());
adminInfo.append("processing person" + person);
return person;
}
};
}
#Bean
public FlatFileItemReader<Person> reader() {
FlatFileItemReader<Person> reader = new FlatFileItemReader<>();
reader.setResource(new FileSystemResource("simple-data.csv"));
reader.setLinesToSkip(1);
reader.setLineMapper(new DefaultLineMapper() {
{
//3 columns in each row
setLineTokenizer(new DelimitedLineTokenizer() {
{
setNames(new String[] { "name", "surname", "age" });
}
});
//Set values in Employee class
setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
{
setTargetType(Person.class);
}
});
}
});
return reader;
}
#Bean
public ItemWriter<Person> writer(){
ItemWriter<Person> writer = new ItemWriter<Person>() {
#Override
public void write(List<? extends Person> messages) throws Exception {
for (Person msg : messages) {
logger.log(Level.INFO, "Writing the data " + msg);
}
}
};
return writer;
}
#Bean
public ResourcelessTransactionManager transactionManager() {
return new ResourcelessTransactionManager();
}
#Bean
public JobRepository jobRepository(ResourcelessTransactionManager transactionManager) throws Exception {
MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(transactionManager);
mapJobRepositoryFactoryBean.setTransactionManager(transactionManager);
return mapJobRepositoryFactoryBean.getObject();
}
#Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
simpleJobLauncher.setJobRepository(jobRepository);
return simpleJobLauncher;
}
}
my pom.xml is:
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.13.RELEASE</spring.version>
<spring.batch>3.0.8.RELEASE</spring.batch>
<javax.servlet>3.0.1</javax.servlet>
<spring.test>3.2.4.RELEASE</spring.test>
<junit.version>4.11</junit.version>
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<build>
<finalName>SomeNAme</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
<testSourceDirectory>src/test</testSourceDirectory>
</build>
<dependencies>
<!--SPRING-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</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-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--SPRING-BATCH CONFIGURED-->
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>${spring.batch}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.1.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--JPA-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.9.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--DATABASE-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.0.1.Final</version>
<exclusions>
<exclusion>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.1_spec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
<exclusions>
<exclusion>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.1_spec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.0.1.Final</version>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jta_1.1_spec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.oracle.odb</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2.0</version>
</dependency>
<!--TEST-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- SERVLET-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet}</version>
<scope>provided</scope>
</dependency>
<!--JACKSON AND XML-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
<!--APACHE-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!--TEST-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<!--LOG4J-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
</project>
So, this is libraries issue? (I tried to comment all spring-batch code and leaves only depedency in pom - and it starts to work..
my beans related with database is:
#Configuration
#EnableTransactionManagement
#EnableJpaAuditing
#EnableJpaRepositories(basePackages = {"persistence"})
#ComponentScan(basePackages = {"persistence""})
public class PersistenceConfig {
#Bean
#Resource(type = DataSource.class, lookup = "jdbc/MyDataBase", name = "jdbc/MyDataBase")
public DataSource dataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/MyDataBase");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource());
entityManager.setPackagesToScan(PACKAGE_WITH_JPA_ENTITIES);
entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManager.setJpaProperties(getHibernateProperties());
log.info("Entity Manager configured.");
return entityManager;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
//Set properties hibernate
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "none");
properties.put("org.hibernate.envers.do_not_audit_optimistic_locking_field", false);
properties.put("verifyServerCertificate", false);
properties.put("useSSL", false);
properties.put("requireSSL", false);
properties.put("useLegacyDatetimeCode", false);
properties.put("useUnicode", "yes");
properties.put("characterEncoding", "UTF-8");
properties.put("serverTimezone", "UTC");
properties.put("useJDBCCompliantTimezoneShift", true);
return properties;
}
}
I think that reason is in Transaction management, but can't to configure it correct way. If I use this way for creating transaction management:
public PlatformTransactionManager getTransactionManager() throws Exception {
return new WebSphereUowTransactionManager();
}
or
public PlatformTransactionManager getTransactionManager() throws Exception {
return new DataSourceTransactionManager(dataSource);
}
I have an error message
Error 500: org.springframework.web.util.NestedServletException:
Request processing failed; nested exception is
org.springframework.jdbc.BadSqlGrammarException:
PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID,
JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? and JOB_KEY = ?];
nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table
or view does not exist
this is because I have no temp table for spring batch..
If I used
public PlatformTransactionManager getTransactionManager() throws Exception {
return new ResourcelessTransactionManager();
}
spring - batch work, but doesn't work saving jpa entities..
Root cause is not in dependecy conflict. The reason is that there are 2 bean with same name for JPA and for spring-batch. So, creating bean with different name is solved a problem.
#Bean
public ResourcelessTransactionManager springBatchTransactionManager() {
return new ResourcelessTransactionManager();
}
#Bean
public JobRepository jobRepository(ResourcelessTransactionManager springBatchTransactionManager) throws Exception {
MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(springBatchTransactionManager);
mapJobRepositoryFactoryBean.setTransactionManager(springBatchTransactionManager);
return mapJobRepositoryFactoryBean.getObject();
}

Mybatis-Spring Java Configuration #MapperScan Annotation

I am trying to set up my mybatis-spring like shown in the following examples:
1)Code from a previous answer on stackoverflow, a few answer down
(MyBatis-Spring + #Configuration - Can't autowire mapper beans)
#Configuration
#MapperScan("org.mybatis.spring.sample.mapper")
public class AppConfig
{
#Bean
public DataSource dataSource()
{
return new EmbeddedDatabaseBuilder().addScript("schema.sql").build();
}
#Bean
public DataSourceTransactionManager transactionManager()
{
return new DataSourceTransactionManager(dataSource());
}
#Bean
public SqlSessionFactory sqlSessionFactory() throws Exception
{
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
}
2)Code from their documentation (http://www.mybatis.org/spring/mappers.html)
Usage:
public class FooServiceImpl implements FooService {
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User doSomeBusinessStuff(String userId) {
return this.userMapper.getUser(userId);
}
}
Registering Mapper with #MapperScan:
#Configuration
#MapperScan("org.mybatis.spring.sample.mapper")
public class AppConfig {
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().addScript("schema.sql").build()
}
#Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
}
My code which isn't working is as shown below:
My Application with nested AppConfig:
#SpringBootApplication
#MapperScan(basePackages="com.tjwhalen.game.service.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//#MapperScan(basePackages="com.tjwhalen.game.service.dao")
public class AppConfig {
#Autowired
DataSource datasource;
#Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(datasource);
}
#Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(datasource);
//sqlSessionFactory.setTypeAliasesPackage("com.tjwhalen.game.model");
return (SqlSessionFactory) sqlSessionFactory.getObject();
}
#Bean
public ItemSummaryDbService itemSummaryDbService() {
return new ItemSummaryDbServiceImpl();
}
}
}
My service:
public class ItemSummaryDbServiceImpl implements ItemSummaryDbService {
#Autowired
private ItemSummaryMapper itemSummaryMapper;
public void setItemSummaryMapper(ItemSummaryMapper itemSummaryMapper) {
this.itemSummaryMapper = itemSummaryMapper;
}
public void writeItemSummarys(List<ItemSummary> itemSummarys) {
for(ItemSummary itemSummary : itemSummarys) {
itemSummaryMapper.insertItemSummary(itemSummary);
}
}
public List<ItemSummary> lookupItemSummarys() {
return itemSummaryMapper.selectItemSummarys();
}
}
My mapper in the package indicated by the #MapperScan annotaion:
package com.tjwhalen.game.service.dao;
import java.util.List;
import com.tjwhalen.game.model.ItemSummary;
public interface ItemSummaryMapper {
public void insertItemSummary(ItemSummary itemSummary);
public List<ItemSummary> selectItemSummarys();
}
My usage:
public class LoadItems implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(LoadItems.class);
#Autowired
private ItemSummaryDbService service;
public void run(String... arg0) throws Exception {
logger.info("LoadItems is running");
ArrayList<ItemSummary> list = new ArrayList<ItemSummary>();
list.add(new ItemSummary(1, "one", 1));
service.writeItemSummarys(list);
}
}
My stacktrace:
java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransactionFactory.newTransaction(Ljava/sql/Connection;Z)Lorg/apache/ibatis/transaction/Transaction;
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:77) ~[ibatis-core-3.0.jar:na]
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession(DefaultSqlSessionFactory.java:40) ~[ibatis-core-3.0.jar:na]
at org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:102) ~[mybatis-spring-1.3.0.jar:1.3.0]
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:429) ~[mybatis-spring-1.3.0.jar:1.3.0]
at com.sun.proxy.$Proxy41.insert(Unknown Source) ~[na:na]
at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:279) ~[mybatis-spring-1.3.0.jar:1.3.0]
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:54) ~[ibatis-core-3.0.jar:na]
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:35) ~[ibatis-core-3.0.jar:na]
at com.sun.proxy.$Proxy42.insertItemSummary(Unknown Source) ~[na:na]
at com.tjwhalen.game.service.impl.ItemSummaryDbServiceImpl.writeItemSummarys(ItemSummaryDbServiceImpl.java:32) ~[classes/:na]
at com.tjwhalen.game.loader.LoadItems.run(LoadItems.java:28) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:782) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:769) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at com.tjwhalen.game.Application.main(Application.java:37) [classes/:na]
And finally 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.tjwhalen.game</groupId>
<artifactId>Runescape-App</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>8.4-702.jdbc4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-core -->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-core</artifactId>
<version>3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
</dependency> -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.batch/spring-batch-infrastructure -->
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I've had a lot of problems in the past regarding incorrect pom.xml, so I looked at each dependency involving database access and made sure the project had the correct provided dependencies. I also checked that the versions were the same as mentioned in the provided dependencies.
What does the error message AbstractMethodError indicate?
Feel free to ask any clarifying questions
I figured it out. I added a dependency
<!-- https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-core -->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-core</artifactId>
<version>3.0</version>
</dependency>
and removing it fixed. I don't know why this dependency was here, I went through and checked the rest of my dependencies to see if they depended on ibatis-core and they didn't.
So it was an oversight on my part, and shows that AbstractMethodError is likely a dependency issue, and that is the first thing that should be checked when facing it

Null Autowired Spring Bean (Cassandra Repository) in Service

I am getting a NullPointerException on an autowired bean in a service class. The class I'm trying to autowire is a Cassandra Repository.
My main class Application.java
#SpringBootApplication
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My Cassandra configuration CassandraConfig.java
#Configuration
#EnableCassandraRepositories(basePackages = "com.myretail")
public class CassandraConfig extends AbstractCassandraConfiguration {
#Override
protected String getKeyspaceName() {
return "myretail";
}
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster =
new CassandraClusterFactoryBean();
cluster.setContactPoints("127.0.0.1");
cluster.setPort(9042);
return cluster;
}
#Bean
public CassandraMappingContext cassandraMapping()
throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
#Bean
public ProductService productService() {
return new ProductService();
}
}
My repository (dao) ProductPriceRepository.java
public interface ProductPriceRepository extends CassandraRepository<ProductPrice> {
#Query("select * from productprice where productId = ?0")
ProductPrice findByProductId(String productId);
}
My service class ProductService.java
#Path("/product")
#Component
public class ProductService {
#Autowired
ProductPriceRepository productPriceRepository;
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Product getTargetProduct(#PathParam("id") String productId) {
String urlString = "https://api.vendor.com/products/v3/" + productId + "?fields=descriptions&id_type=TCIN&key=43cJWpLjH8Z8oR18KdrZDBKAgLLQKJjz";
JSONObject json = null;
try {
json = new JSONObject(JsonReader.getExternalJsonResponse(urlString));
} catch (JSONException e) {
e.printStackTrace();
}
Product product = new Product();
product.setId(productId);
try {
JSONObject productCompositeResponse = json.getJSONObject("product_composite_response");
JSONArray items = productCompositeResponse.getJSONArray("items");
JSONObject item = items.getJSONObject(0);
JSONObject onlineDescription = item.getJSONObject("online_description");
product.setName(onlineDescription.getString("value"));
} catch (JSONException e) {
e.printStackTrace();
}
ProductPrice productPrice = productPriceRepository.findByProductId(productId);
product.setProductPrice(productPrice);
return product;
}
}
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myretail</groupId>
<artifactId>MyRetail</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>MyRetail</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-spring</artifactId>
<version>2.1.9.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-shaded</artifactId>
<version>2.1.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hectorclient</groupId>
<artifactId>hector-core</artifactId>
<version>2.0-0</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.18.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.3.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>my-tomcat</server>
<path>/myRetail</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
It is my understanding that the annotations should pick up the repository and create the bean based off of the #EnableCassandraRepositories annotation. The #Autowired ProductPriceRepository in ProductService.java is always null though when I run this on tomcat. HOWEVER, if I run a junit test against the service call, the bean is properly created, the object is not null, and the tests pass (via #ContextConfiguration annotation).
I've looked at a couple different patterns that I thought might help, but none of them have worked. I can't create an implementation of my interface because Cassandra handles that internally and I'm forced to implement the Cassandra methods.
I feel like something is just slightly off with the annotations somewhere. Any ideas?
The problem is with your pom.xml
For spring-boot Cassandra application, you have to include below dependencies and parent pom in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
</dependencies>

Categories

Resources