if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope - spring

I am using Spring Boot v2.6.2 and Spring Batch and getting below error:
ustom destroy method 'close' on bean with name 'compositeItemWriter' threw an exception: org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.xmlDelegateItemWriter': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope
MainApp.java
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.support.CompositeItemWriter;
import org.springframework.batch.item.support.builder.CompositeItemWriterBuilder;
import org.springframework.batch.item.xml.StaxEventItemWriter;
import org.springframework.batch.item.xml.builder.StaxEventItemWriterBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.oxm.xstream.XStreamMarshaller;
import javax.sql.DataSource;
import java.util.*;
#SpringBootApplication
#EnableBatchProcessing
public class CompositeItemWriterJobApplication {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean(destroyMethod="")
#StepScope
public FlatFileItemReader<Customer> compositeWriterItemReader(#Value("#{jobParameters['customerFile']}") Resource inputFile) {
return new FlatFileItemReaderBuilder<Customer>()
.name("compositeWriterItemReader")
.resource(inputFile)
.delimited()
.names("firstName", "middleInitial", "lastName", "address", "city", "state", "zip", "email")
.targetType(Customer.class)
.build();
}
#Bean(destroyMethod="")
#StepScope
public StaxEventItemWriter<Customer> xmlDelegateItemWriter(#Value("#{jobParameters['outputFile']}") Resource outputFile){
Map<String, Class> aliases = new HashMap<>();
aliases.put("customer", Customer.class);
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.setAliases(aliases);
marshaller.afterPropertiesSet();
return new StaxEventItemWriterBuilder<Customer>()
.name("customerItemWriter")
.resource(outputFile)
.marshaller(marshaller)
.rootTagName("customers")
.build();
}
#Bean
public JdbcBatchItemWriter<Customer> jdbcDelgateItemWriter(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Customer>()
.namedParametersJdbcTemplate(new NamedParameterJdbcTemplate(dataSource))
.sql("INSERT INTO CUSTOMER (first_name, middle_initial, last_name, address, city, state, email) " +
"VALUES(:firstName,:middleInitial, :lastName, :address, :city, :state, :zip, :email)")
.beanMapped()
.build();
}
#Bean
public CompositeItemWriter<Customer> compositeItemWriter() throws Exception {
return new CompositeItemWriterBuilder<Customer>()
.delegates(Arrays.asList(xmlDelegateItemWriter(null),
jdbcDelgateItemWriter(null)))
.build();
}
#Bean
public Step compositeWriterStep() throws Exception {
return this.stepBuilderFactory.get("compositeWriterStep")
.<Customer, Customer>chunk(10)
.reader(compositeWriterItemReader(null))
.writer(compositeItemWriter())
.build();
}
#Bean
public Job compositeWriterJob() throws Exception {
return this.jobBuilderFactory.get("compositeWriterJob")
.start(compositeWriterStep())
.build();
}
public static void main(String[] args) {
SpringApplication.run(CompositeItemWriterJobApplication.class,
"customerFile=/data/customer.csv",
"outputFile=/output/customer.xml");
}
}
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>composite-item-writer-job</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>composite-item-writer-job</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.18</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Note: I also used #Scope(value = "step", proxyMode = ScopedProxyMode.TARGET_CLASS), but no luck.
Bean
#Bean
public org.springframework.batch.core.scope.StepScope stepScope() {
final StepScope stepScope = new org.springframework.batch.core.scope.StepScope();
stepScope.setAutoProxy(true);
return stepScope;
}
application.yml
spring:
batch:
initialize-schema: always
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: 'root'
password: 'root'
platform: mysql
main:
allow-bean-definition-overriding: true
Things are still not working!

I encountered the same problem. For me, the solution was to add “#StepScope” on the methods calling the method with “#StepScope” and the jobParameters. In this example, I would try to annotate the method compositeItemWriter with “#StepScope”. You will probably need to do it with jdbcDelgateItemWriter.
#Bean
#StepScope
public CompositeItemWriter<Customer> compositeItemWriter() throws Exception {
return new CompositeItemWriterBuilder<Customer>()
.delegates(Arrays.asList(xmlDelegateItemWriter(null),
jdbcDelgateItemWriter(null)))
.build();
}

Related

hibernate ClassCastException with mvn spring-boot:run

when I start the server using the jar:
java -jar core-0.0.1-SNAPSHOT.jar
then everything works fine.
But when i use the maven plugin:
mvn spring-boot:run
then i get the following error message:
2020-09-28 23:09:46.633 DEBUG 13970 --- [ main] d.j.p.server.core.ServerApplication : Running with Spring Boot v2.1.6.RELEASE, Spring v5.1.8.RELEASE
2020-09-28 23:09:46.634 INFO 13970 --- [ main] d.j.p.server.core.ServerApplication : No active profile set, falling back to default profiles: default
2020-09-28 23:09:49.120 ERROR 13970 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message:
Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]:
Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseTransactionManager' defined in class path resource [de/jwt/project/server/core/config/BaseDataSourceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]:
Factory method 'baseTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'baseEntityManager' defined in class path resource [de/jwt/project/server/core/config/BaseDataSourceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]:
Factory method 'baseEntityManager' threw exception; nested exception is java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.lang.reflect.ParameterizedType
(java.lang.Class and java.lang.reflect.ParameterizedType are in module java.base of loader 'bootstrap')
2020-09-28 23:09:49.167 WARN 13970 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2020-09-28 23:09:49.188 ERROR 13970 --- [ main] o.s.boot.SpringApplication : Application run failed
Unfortunately I have no idea what the cause can be,
i am grateful for every help
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>de.jwt.project.server</groupId>
<artifactId>core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Server</name>
<description>Server</description>
<properties>
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
<project.reporting.outputEncoding>ISO-8859-1</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<!--<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-bom</artifactId>
<version>Bean-SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>-->
<repositories>
<repository>
<id>jcenter</id>
<url>https://jcenter.bintray.com/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-bom</artifactId>
<version>Bean-SR3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
<!-- send email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</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-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>de.jwt.project.remoteservice</groupId>
<artifactId>de.jwt.project.remoteservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/net.imagej/ij -->
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>1.52i</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--
<dependency>
<groupId>de.agital.project.caritas</groupId>
<artifactId>de.agital.project.caritas</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>-->
<dependency>
<groupId>org.wickedsource.docx-stamper</groupId>
<artifactId>docx-stamper</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>6.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
#SpringbootApplication main class
package de.jwt.project.server.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.naming.NoPermissionException;
import javax.servlet.Filter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import de.jwt.project.database.components.ModelResource;
import de.jwt.project.database.components.Referenz;
import de.jwt.project.database.tenant.Account;
import de.jwt.project.database.tenant.Geschaeftspartner;
import de.jwt.project.database.tenant.GespeicherteAbfrage;
import de.jwt.project.database.tenant.Instanz;
import de.jwt.project.database.tenant.Instanzwert;
import de.jwt.project.database.tenant.Rolle;
import de.jwt.project.database.tenant.Team;
import de.jwt.project.database.tenant.Vertrag;
import de.jwt.project.database.tenant.VertragInstanzBez;
import de.jwt.project.database.types.OperationsForQuery;
import de.jwt.project.remoteservice.components.ReferenzHierachy;
import de.jwt.project.server.core.dao.tenant.AccountDao;
import de.jwt.project.server.core.dao.tenant.RolleDao;
import de.jwt.project.server.core.migration.MetadataGenerator;
import de.jwt.project.server.core.multitenant.MultiTenantFilter;
import de.jwt.project.server.core.service.AccountService;
import de.jwt.project.server.core.service.ResourceService;
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
#SuppressWarnings("unused")
public class ServerApplication {
private static Account login(final ConfigurableApplicationContext context, String username, String password,
String tenant) {
final AccountDao accountDao = context.getBean(AccountDao.class);
final RolleDao rolleDao = context.getBean(RolleDao.class);
final AccountService accountService = context.getBean(AccountService.class);
final MetadataGenerator metaGen = context.getBean(MetadataGenerator.class);
Account admin = null;
try {
admin = (Account) accountService.loadUserByUsername(username);
} catch (UsernameNotFoundException e) {
e.printStackTrace();
}
if (admin == null) {
admin = new Account();
admin.setUsername(username);
admin.setPassword(password);
Rolle rolle = rolleDao.findByDescription("Administrator");
if (rolle == null) {
rolle = new Rolle();
rolle.setDescription("Administrator");
rolle = rolleDao.save(rolle);
}
Set<Rolle> rollen = new HashSet();
rollen.add(rolle);
admin = accountService.save(admin);
admin.setRoles(rollen);
admin = accountService.save(admin);
}
metaGen.execute(admin, "metadaten_caritas.xml");
return admin;
}
private static void encryptPW(final ConfigurableApplicationContext context) {
final BCryptPasswordEncoder enc = new BCryptPasswordEncoder();
final AccountDao accountDao = context.getBean(AccountDao.class);
// -------------------------------
final List<Account> lstAccount = accountDao.findAll();
for (final Account account : lstAccount) {
if (!account.isEncrypted()) {
account.setPassword(enc.encode(account.getPassword()));
account.setEncrypted(true);
accountDao.save(account);
}
}
}
public static void main(final String[] args) throws Throwable {
final ConfigurableApplicationContext context = SpringApplication.run(ServerApplication.class, args);
Properties properties = new Properties();
try (InputStream inputStream = ServerApplication.class.getClassLoader().getResourceAsStream("application.properties")) {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
String username = properties.getProperty("backenduser");
String pw = properties.getProperty("backenduserpassword");
Account account = login(context, username, pw, "carritas_db");
// Verschlüssele Passwörter im Klartext
encryptPW(context);
//createAuskunftverlangen(context, account);
}
private static void createAuskunftverlangen(ConfigurableApplicationContext context, Account account) {
final ResourceService ressourceService = context.getBean(ResourceService.class);
try {
GespeicherteAbfrage abfrage = (GespeicherteAbfrage) ressourceService
.getByDescription(GespeicherteAbfrage.class, "Auskunftsverlangen");
if (abfrage != null) {
return;
}
ReferenzHierachy hierachy = new ReferenzHierachy(Instanzwert.class, true);
hierachy.addJoin(Instanz.class, "instanz", "id", "instanz", null);
hierachy.addJoin(VertragInstanzBez.class, "id", "instanz", "vib", "instanz");
hierachy.addJoin(Vertrag.class, "vertrag", "id", "vertrag", "vib");
hierachy.addCondition(hierachy.createFilter(Referenz.class, "geschaeftspartner", OperationsForQuery.EQUALS,
new Geschaeftspartner().toReferenz(), "instanz"));
hierachy.addAdditionalField(String.class, "wert", null, "gespeicherter Wert");
hierachy.addAdditionalField(ModelResource.class, "referenz", null, "gespeicherte Referenz");
hierachy.addAdditionalField(String.class, "vertragsnummer", "vertrag", "Vertragsnummer");
hierachy.addAdditionalField(String.class, "description", "vertrag", "Vertrag");
Team team = new Team(account);
abfrage = new GespeicherteAbfrage();
abfrage.setBesitzer(team.toReferenz());
abfrage.setDescription("Auskunftsverlangen");
abfrage.setAbfrage(hierachy.serialize());
abfrage = (GespeicherteAbfrage) ressourceService.save(abfrage);
} catch (IOException | NoPermissionException | ClassNotFoundException e) {
e.printStackTrace();
return;
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean someFilterRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(someFilter());
registration.addUrlPatterns("/api/auth/login/*");
registration.setName("MultiTenantFilter");
registration.setOrder(1);
return registration;
}
public Filter someFilter() {
return new MultiTenantFilter();
}
}
BaseDataSourceConfig:
package de.jwt.project.server.core.config;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#EnableJpaRepositories(
basePackages = "de.jwt.project.server.core.dao.base",
entityManagerFactoryRef = "baseEntityManager",
transactionManagerRef = "baseTransactionManager"
)
public class BaseDataSourceConfig {
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean baseEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("persistence.base");
em.setDataSource(baseDataSource());
em.setPackagesToScan("de.jwt.project.database.base", "de.jwt.project.database.components");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.afterPropertiesSet();
return em;
}
#Primary
#Bean
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource baseDataSource() {
DataSource ds = DataSourceBuilder.create()
.build();
return ds;
}
#Primary
#Bean
public PlatformTransactionManager baseTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
baseEntityManager().getObject());
return transactionManager;
}
}
The image shows the point where the exception is thrown.
The cast exception is thrown in the AttributeConverterDefinition.resolveType() method.
And her the code from the ReferenzConverter.class.
This is the class which cause the cast exception.
package de.jwt.project.database.components;
import java.util.UUID;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter(
autoApply = true
)
public class ReferenzConverter<T extends ModelResource> implements AttributeConverter<Referenz<T>, UUID> {
public ReferenzConverter() {
}
public UUID convertToDatabaseColumn(Referenz<T> attribute) {
return attribute == null ? null : attribute.getId();
}
public Referenz<T> convertToEntityAttribute(UUID dbData) {
if (dbData == null) {
return null;
} else {
Referenz ref = new Referenz(dbData);
return ref;
}
}
}
.....................................................

postgresql jdbc driver not found

I am working with spring, hibernate, postgresql and maven for an application, but when I build it I have this error :
Error creating bean with name 'dataSource' defined in com.rovb.webstore.config.RootApplicationContextConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Required key 'org.postgresql.Driver' not found
I am working with STS 4.0 and my code is:
DispatcherServletInitializer.java
package com.rovb.webstore.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootApplicationContextConfig.class };
//return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebApplicationContextConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/"};
}
}
RootApplicationContextConfig.java
package com.rovb.webstore.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.rovb.webstore.config" })
public class RootApplicationContextConfig {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.rovb.webstore.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("org.postgresql.Driver"));
dataSource.setUrl(environment.getRequiredProperty("jdbc:postgresql://localhost:5432/tetra"));
dataSource.setUsername(environment.getRequiredProperty("postgres"));
dataSource.setPassword(environment.getRequiredProperty("postgres"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("org.hibernate.dialect.PostgreSQLDialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("true"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("true"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
WebApplicationContextConfig.java
package com.rovb.webstore.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan("com.rovb.webstore")
public class WebApplicationContextConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
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.packt</groupId>
<artifactId>webstore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<springframework.version>4.3.0.RELEASE</springframework.version>
<servlets.version>3.1.0</servlets.version>
<jstl.version>1.2</jstl.version>
<hibernate.version>5.1.0.Final</hibernate.version>
</properties>
<dependencies>
<!-- SPRING -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
<scope>compile</scope>
</dependency>
<!-- JAVA -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlets.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1205-jdbc42</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>

Spring boot application deployed in Wildfly "Failed to instantiate WebApplicationInitializer class"

I am using IntelliJ IDEA and building a spring boot application, i.e. a REST web service. Everything seems ok when running the application from the IDE. When I try to deploy it on WildFly 14, I get the following error:
{"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\".war\".undertow-deployment" => "java.lang.RuntimeException: javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
Caused by: java.lang.RuntimeException: javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
Caused by: javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
Caused by: java.lang.NoSuchMethodException: com.foo.Application.()"}}
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.foo.<application-name></groupId>
<artifactId><application-name></artifactId>
<version>xxx</version>
<name>Application name</name>
<description>Application description
</description>
<properties>
<start-class>com.foo.Application</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.5.4</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<!-- update Hibernate dependency on Javassist to 3.23.1 for Java 11 compatibility -->
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.1-GA</version>
</dependency>
<dependency>
<!-- update Mockito dependency for Java 11 compatibility -->
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.22.0</version><!--$NO-MVN-MAN-VER$ -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--<configuration>
<executable>true</executable>
<skipTests>true</skipTests>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>-->
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
My com.foo.Application class:
package com.foo;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.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.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#Configuration
#EnableJpaRepositories("com.foo.repositories")
#EntityScan("com.foo.entities")
#EnableTransactionManagement
#ComponentScan({ "com.foo.services", "com.foo.controllers" })
#PropertySource("classpath:application.properties")
public class Application extends SpringBootServletInitializer {
private final Logger logger1 = LoggerFactory.getLogger(Application.class);
#Autowired
public Application(Environment env) {
this.env = env;
}
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(Application.class);
SpringApplication.run(Application.class, args);
log.trace("Application started");
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
logger1.trace("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
logger1.trace(beanName);
}
};
}
// Database initialization is organized according to the tutorial in https://www.baeldung.com/spring-jpa-test-in-memory-database
private final Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Objects.requireNonNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.foo.entities");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
/*hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));*/
return hibernateProperties;
}
#Bean
public ModelMapper modelMapper() {
ModelMapper mm = new ModelMapper();
mm.addConverter(new InteractionConverter());
return mm;
}
public static String getVersion() throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
String version;
if ((new File("pom.xml")).exists()) {
try (FileReader pomFileReader = new FileReader("pom.xml")) {
Model model = reader.read(pomFileReader);
version = model.getVersion();
}
} else {
try (InputStream stream = Application.class.getResourceAsStream(
"/META-INF/maven/com.foo.application-name/application-name/pom.xml")) {
InputStreamReader pomFileReader = new InputStreamReader(stream);
Model model = reader.read(pomFileReader);
version = model.getVersion();
}
}
return version;
}
public static String getDescription() throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
String description;
if ((new File("pom.xml")).exists()) {
try (FileReader pomFileReader = new FileReader("pom.xml")) {
Model model = reader.read(pomFileReader);
description = model.getDescription();
}
} else {
try (InputStream stream = Application.class.getResourceAsStream(
"/META-INF/maven/com.foo.application-name/application-name/pom.xml")) {
InputStreamReader pomFileReader = new InputStreamReader(stream);
Model model = reader.read(pomFileReader);
description = model.getDescription();
}
}
return description;
}
}
If I get it right, the spring application entry point is not visible, but I don't understand why. Is there something wrong with my pom.xml or my Application class?
Tracing the source codes and found that it basically uses the following codes to create an instance of SpringBootServletInitializer:
Constructor ctor = FooInitialializer.class.getDeclaredConstructor();
ctor.newInstance();
That means your SpringBootServletInitializer should have an no-args constructor. So try to add one :
public class Application extends SpringBootServletInitializer {
Application(){}
}

Springboot JdbcTemplate Autowired failed

I'm trying to access database using springboot, however spring application throws an exception below.
Error creating bean with name 'welcomeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate com.mysite.soLexiconWebSpring.jsp.WelcomeController.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Which I think is mainly
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency
that indicates that no bean is created from application config file.
However I googled for a while and got no luck. Can anybody tell me how to inject JdbcTemplate Correctly?
Here is my POM:
<?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>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>
<artifactId>soLexiconWebSpring</artifactId>
<groupId>com.mysite</groupId>
<packaging>war</packaging>
<name>Spring Boot Web JSP Sample</name>
<description>Spring Boot Web JSP Sample</description>
<version>0.0.1-SNAPSHOT</version>
<url>http://projects.spring.io/spring-boot/</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>http://www.spring.io</url>
</organization>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
<m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
</build>
</project>
Application.properties
spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp
application.message=Hello SuperLucky
#spring.datasource basic database parameter
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/so_lexicon
spring.datasource.username=xxx
spring.datasource.password=xxx
#set data pooling provider to org.apache.tomcat
spring.datasource.type = org.apache.tomcat.jdbc.pool.DataSource
#tomcat datasource settings
spring.datasource.tomcat.initial-size=20
spring.datasource.tomcat.max-wait=2000
spring.datasource.tomcat.max-active=100
spring.datasource.tomcat.max-idle=16
spring.datasource.tomcat.min-idle=4
spring.datasource.tomcat.test-on-connect=true
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-on-return=true
Application
package com.mysite.soLexiconWebSpring.jsp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class SampleWebJspApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleWebJspApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleWebJspApplication.class, args);
}
}
Controller
package com.mysite.soLexiconWebSpring.jsp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.mysite.soLexiconWebSpring.jsp.beans.FullLexiconRowBean;
import com.mysite.soLexiconWebSpring.jsp.beans.LoginTokenBean;
import com.mysite.soLexiconWebSpring.jsp.dao.LexiconDaoImpl;
import com.mysite.soLexiconWebSpring.jsp.utils.DBUtils;
#Controller
public class WelcomeController {
#Value("${application.message:Hello World}")
private String message = "Hello World";
#Autowired
private JdbcTemplate dataSource;
#Autowired
private DBUtils dbUtils;
#RequestMapping("/soLexiconWebSpring")
public String welcome(Map<String, Object> model) {
model.put("time", new Date());
model.put("message", this.message);
return "welcome";
}
#RequestMapping("/soLexiconWebSpring/login")
public String login(#RequestParam("username") String username, #RequestParam("password") String password, Map<String, Object> model)
{
LoginTokenBean loginToken = new LoginTokenBean();
loginToken.setUsername(username);
loginToken.setPassword(password);
model.put("loginToken", loginToken);
LexiconDaoImpl lexRowDao = new LexiconDaoImpl(dataSource);
List<FullLexiconRowBean> result = lexRowDao.getLexiconRow(1, 5);
if(result != null) model.put("result", result);
else model.put("result", dbUtils.getLastException().toString());
dbUtils.setLastException(new Exception("A B C"));
model.put("dbUtils", dbUtils);
return "lexicon";
}
}
Thanks for #mrkemelpanic, I updated my project to springboot 2.0.4 (with some effort), and it finally works. So it might be a 1.0.2 bug or something.
Thanks.

Spring Boot WebSocket with embedded ActiveMQ Broker

I tried to change an web application from simple broker to an embedded ActiveMq Broker with stomp using Spring boot 1.5.4 but always getting an error on start up
Caused by: java.lang.IllegalArgumentException: No handlers
at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.start(SubProtocolWebSocketHandler.java:244) ~[spring-websocket-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:175) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 15 common frames omitted
I reduced the failure with an simple example
POM File *
<?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>websocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>websocket</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</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-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-stomp</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-net</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.2.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application Class
package com.example.websocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
}
WebSocketConfig Class
package com.example.websocket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;
#Configuration
#EnableWebSocket
#EnableWebSocketMessageBroker
#EnableJms
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {
#Value("${spring.activemq.user}")
private String mqUser;
#Value("${spring.activemq.password}")
private String mqPasword;
#Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic") //
.setRelayHost("localhost") //
.setRelayPort(61613) //
.setClientLogin(mqUser) //
.setClientPasscode(mqPasword) //
;
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
application.yml
spring:
activemq:
broker-url: stomp://localhost:61613
user: user
password: pass
Someone knows my mistake?
I found the solution. My problem was the EnableWebSocketMessageBroker Annotation and missing deployment of ActiveMQ Broker
Remove the application.yml and change WebSocketConfig class to
package com.example.websocket;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;
#Configuration
#EnableWebSocket
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {
#Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic") //
.setRelayHost("localhost") //
.setRelayPort(61613);
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
#Bean(initMethod = "start", destroyMethod = "stop")
public BrokerService broker() throws Exception {
final BrokerService broker = new BrokerService();
broker.addConnector("stomp://localhost:61613");
broker.setPersistent(false);
final ManagementContext managementContext = new ManagementContext();
managementContext.setCreateConnector(true);
broker.setManagementContext(managementContext);
return broker;
}
}
works for me.

Resources