Error creating bean with name 'mongoTemplate' while connecting mongodb through Spring - java

I am trying to connect mongoDb with Spring's mongoTemplate. I also tried changing version of 'spring-data-mongodb' from 1.7.2.RELEASE to 1.8.2.RELEASE, but even that didn't work.
Below is my code as used in the project.
Here's 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.storeApp</groupId>
<artifactId>storeApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Store Application</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>storeApp</finalName>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
My SpringMongoConfig file
package com.storeApp.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
#Configuration
public class SpringMongoConfig1 {
public #Bean
MongoDbFactory mongoDbFactory() throws Exception{
return new SimpleMongoDbFactory(new MongoClient(), "storeApp");
}
public #Bean
MongoTemplate mongoTemplate() throws Exception{
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
// ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
// MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
}
This is my main class
package com.storeApp.core;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.storeApp.config.SpringMongoConfig1;
import com.storeApp.config.SpringMongoConfig2;
import com.storeApp.model.Store;
public class StoreMainApp {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig1.class);
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
Store store = new Store("Sample store 1", "Street 1", "City 1", (float) 35.4);
System.out.println("into main method");
// mongoOperation.save(store);
}
}
Stacktrace :
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:12}] to 127.0.0.1:27017
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=1546838}
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in com.storeApp.config.SpringMongoConfig1: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at com.storeApp.core.StoreMainApp.main(StoreMainApp.java:20)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 13 more
Caused by: java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
at org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper.<clinit>(DefaultMongoTypeMapper.java:49)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.<init>(MappingMongoConverter.java:111)
at org.springframework.data.mongodb.core.MongoTemplate.getDefaultMongoConverter(MongoTemplate.java:2039)
at org.springframework.data.mongodb.core.MongoTemplate.<init>(MongoTemplate.java:217)
at org.springframework.data.mongodb.core.MongoTemplate.<init>(MongoTemplate.java:202)
at com.storeApp.config.SpringMongoConfig1.mongoTemplate(SpringMongoConfig1.java:25)
at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96.CGLIB$mongoTemplate$0(<generated>)
at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96$$FastClassBySpringCGLIB$$52d3ef2d.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96.mongoTemplate(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 14 more
Not getting where is the problem...

You only need below dependency and it will bring you all needed jars.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
The error java.lang.NoSuchMethodError you are getting is for ClassTypeInformation class. Please check whether spring-data-commons-1.12.3.RELEASE.jar is present after you build your project. If not, then try cleaning up your build environment and update maven project.

A little late to the party, but here is what you need.
If you are trying to use a custom data manipulation rather than using the default inbuilt mongo repositories, then you need a mongoTemplate (kind of jdbc template but lets you define your own implementation of the client, i.e, the mongo client , in this case) and optionally mongoOperations on top of it(Mongo Operations is kind of a wrapper on top of the mongoTemplate)
You need the following dependencies - pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
MongoConfig.java
#PropertySource("classpath:application.properties")
public class MongoConfig{
#Value("${spring.data.mongodb.host}")
private String mongoHost;
#Value("${spring.data.mongodb.port}")
private String mongopPort;
#Value("${spring.data.mongodb.database}")
private String mongoDB;
/*Client vs FactoryClient
*
* Factory bean that creates the com.mongodb.MongoClient instance
*
* Classes attributed with #Repostiory may throw mongo related exceptions. Declaring an instance of MonogClientFactoryBean
* helps in translating them to spring data exceptions which can then be caught using #ExceptionHandling
* */
public #Bean MongoClientFactoryBean mongo() throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
.connectionsPerHost(2000)
.connectTimeout(4000)
//.maxConnectionIdleTime(1000000000)
.maxWaitTime(3000)
.retryWrites(true)
.socketTimeout(4000)
.sslInvalidHostNameAllowed(true)//this is very risky
.build();
mongo.setMongoClientOptions(clientOptions);
return mongo;
}
}
DataSourceConfig.java
#Configuration
#Import(value=MongoClientFactory.class)
public class DataSourceConfig {
#Autowired
Mongo mongo;
#Autowired
Environment env;
#Bean
public String test() {
System.out.println("mongo"+mongo);
return "rer";
}
#Bean
#Qualifier("customMongoTemplate")
public MongoTemplate mongoTemplate() {
//MongoClient is the actual pool used by mongo. Create it using client factory then, autoclosing of threads are handled on its own
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
MongoTemplate template = new MongoTemplate(factory);
return template;
}
#Bean
#Qualifier(value="customMongoOps")
public MongoOperations mongoOps() {
MongoOperations ops = mongoTemplate();
return ops;
}
#Bean
public MongoDbFactory factory() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
return factory;
}
// #Bean
// public GridFsTemplate gridFsTemplate() {
// return new GridFsTemplate(mongo, converter)
// }
}
This should successfully create the mongoTemplate and mongoOperations and you should be able to make use of them in your DAO or service and access them.
PersonService.java
#Service
public class PersonService {
#Autowired
private PersonRepository personRepo;
#Autowired
PersonSequenceServiceImpl seqService;
#Autowired
#Qualifier(value="customMongoOps")
MongoOperations mongoOps;
public List<Person> findAllPersons() {
return personRepo.findAll();
}
public List<Person> createAndFindAllPersons() {
Person p1 = new Person( "another1", "ll1", 30);
Person p2 = new Person( "another2", "ll2", 30);
if(!mongoOps.collectionExists(Person.class)) {
mongoOps.dropCollection("Person_table");
}
//return personRepo.save(person);
System.out.println("P1 data before inserting:"+p1);
mongoOps.insert(Arrays.asList(p1,p2), Person.class);
//mongoOps.dropCollection(Person.class);
return mongoOps.findAll(Person.class);
}
}

I know it's not a technically justified solution. But after trying several alternatives, I just closed Eclipse and deleted all the .m2 folder content.
Then, I retried to import the Project ina new Workspace and compiled.
Surprise! This time it worked :)
Sometimes rebooting works ;)

Related

My springBoot project can't autowire his services with the repositories

As i said in the title i have a springboot project and i'm trying to run it, but when i try to start a clean install using maven i get an error during the test :
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.805 s <<< FAILURE! - in ---myprojectpath---
contextLoads Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myController': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'myRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'myRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
if i ignore this error during the build of mavyour texten i still get a different error when i try tu run my app, i hope that resolving this error ill' be finally able to solve everything.
Anyways here is a part of my controller:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/Mycontroller")
public class Mycontroller{
private static final Logger LOGGER = LoggerFactory.getLogger(Mycontroller.class);
ObjectMapper mapper = new ObjectMapper();
#Autowired
private MyService MyService ;
#GetMapping(value = "/getDatas", produces = "application/json")
public ResponseEntity getDatas() {
try {
DataList responseEntity = new DataList ();
List<Data> datas= MyService.getDatasBean();
..........
} catch (Exception e) {
..........
}
}
}
here is my service:
public interface MyService {
List<Data> getDatasBean() throws Exception;
}
here is the implementation of my service
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.NoResultException;
import java.util.List;
#Service
#Transactional(readOnly = false)
public class MyServiceImpl implements MyService{
private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceImpl.class);
#Autowired
private MyRepository MyRepository ;
public List<Data> getDatasBean() throws Exception {
LOGGER.info(String.format("looking for datas"));
try {
return MyRepository.getAllDatas();
} catch (NoResultException e) {
return null;
} catch (IllegalStateException | IllegalArgumentException e) {
throw new Exception(e);
//throw new BackOfficeEntityException(String.format("error"), e);
}
}
}
here is the repository:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface MyRepository extends CrudRepository<Data, Long> {
#Query("SELECT a " +"FROM Data a ")
List<Data> getAllDatas();
}
as you can read in the log the error is when i bind Myserviceimpl with MyRepository... but i don't understand what i did wrong.... here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven 4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<artifactId>Myproject-jpa</artifactId>
<packaging>jar</packaging>
<name>Myproject-jpa</name>
<dependencies>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>3.0.0</version>
</dependency>
<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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.14</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>2.2.3</version>
</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-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
any help is appreciated, thanks :)
I tried to run the various maven steps (clean,validate,compile,test,package,verify,install) but i got the error that i already pasted, and i tryed to run anyway my application but i get a different error(i think that this last error can be resolvedjust resolving the error that comes up during the test).
i tryed to change the dependencies in the pom.xml but honestly i still don't understand it at all.
No major mistakes in your code. Just use the naming standards(camelCase) properly for your objects. Here is the working code with the proper naming of variables.
MyServiceImpl.java
#Service
#Transactional(readOnly = false)
public class MyServiceImpl implements MyService{
private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceImpl.class);
#Autowired
private MyRepository myRepository ;
public List<Data> getDatasBean() throws Exception {
LOGGER.info(String.format("looking for datas"));
try {
return myRepository.getAllDatas();
} catch (NoResultException e) {
return null;
} catch (IllegalStateException | IllegalArgumentException e) {
throw new Exception(e);
//throw new BackOfficeEntityException(String.format("error"), e);
}
}
}
Mycontroller.java
#RestController
#RequestMapping("/Mycontroller")
public class Mycontroller{
private static final Logger LOGGER = LoggerFactory.getLogger(Mycontroller.class);
ObjectMapper mapper = new ObjectMapper();
#Autowired
private MyService myService ;
#GetMapping(value = "/getDatas", produces = "application/json")
public ResponseEntity getDatas() {
try {
List responseEntity = new ArrayList();
List<Data> datas= myService.getDatasBean();
} catch (Exception e) {
}
..........
}
}

Getting java.lang.NoClassDefFoundError: org/apache/catalina/connector/Connector in wildFly 21.x

I am trying to run a spring boot project which runs perfectly on embedded tomcat but when deployed to wildfly 21.x throws java.lang.NoClassDefFoundError: org/apache/catalina/connector/Connector
Any help would be appreciated.
Below is my code snippet.
Main file:-
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class CdPlaylistadapterApplication {
#Value("${http.port}")
private int httpPort;
public static void main(String[] args) {
SpringApplication.run(CdPlaylistadapterApplication.class, args);
}
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(httpPort);
return connector;
}
}
My pom.xml snippet
<cxf.version>3.4.0</cxf.version>
</properties>
<dependencies>
<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>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
Error:-
Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.att.dtss.playlistadapter.CdPlaylistadapterApplication] from ClassLoader [ModuleClassLoader for Module "deployment.cd-playlistadapter-0.0.1-SNAPSHOT.war" from Service Module Loader]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481)
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:455)
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:151)
... 39 more
Caused by: java.lang.NoClassDefFoundError: org/apache/catalina/connector/Connector
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463)
... 41 more
Caused by: java.lang.ClassNotFoundException: org.apache.catalina.connector.Connector from [Module "deployment.cd-playlistadapter-0.0.1-SNAPSHOT.war" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 45 more
The class org.apache.catalina.connector.Connector is part of Tomcat. In order for your application to work correctly on external servlet containers, the embedded copy of Tomcat must not be on the classpath of the web application (i.e. in /WEB-INF/lib). You set it correctly by setting the scope of the spring-boot-starter-tomcat to provided.
However now you have a problem, because the CdPlaylistadapterApplication has Connector in one of its method signatures and Spring Boot fails while creating an instance of the CdPlaylistadapterApplication class.
To solve it you need to move Tomcat specific configuration to another class (even nested) and protect it with the #ConditionalOnClass annotation:
#SpringBootApplication
public class CdPlaylistadapterApplication extends SpringBootServletInitializer {
#Configuration
#ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class})
static class EmbeddedConfiguration {
#Value("${http.port}")
private int httpPort;
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(httpPort);
return connector;
}
}
public static void main(String[] args) {
SpringApplication.run(CdPlaylistadapterApplication.class, args);
}
}

Hibernate configuration for Mysql 8.0

I'm new in Java! When I run the Junit test the console show me exception and I don't know how to resolve this. What is wrong with my Hibernate configuration? This code perfect works with H2 database, but when I change database and config parameters to Mysql 8.0 the Eclipse return exception. I hope that someone can give me useful advice and explain how resolve this problem. Thanks.
This is my Hibernate Configuration for Mysql 8.0
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#ComponentScan(basePackages= {"com.savaleks.websiteback.dto"})
#EnableTransactionManagement
public class HibernateConfig {
private final static String DATABASE_URL = "jdbc:mysql://localhost:3306/website";
private final static String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private final static String DATABASE_DIALECT = "org.hibernate.dialect.MySQL8Dialect";
private final static String DATABASE_USERNAME = "root";
private final static String DATABASE_PASSWORD = "";
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
// Database connection information
dataSource.setDriverClassName(DATABASE_DRIVER);
dataSource.setUrl(DATABASE_URL);
dataSource.setUsername(DATABASE_USERNAME);
dataSource.setPassword(DATABASE_PASSWORD);
return dataSource;
}
#Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("com.savaleks.websiteback.dto");
return builder.buildSessionFactory();
}
// All Hibernate properties returned in this method
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", DATABASE_DIALECT);
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return null;
}
#Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
And this is console output
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.savaleks.websiteback.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NullPointerException
pom.xml file
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.20.RELEASE</spring.version>
<mysql.version>8.0.13</mysql.version>
<hibernate.version>5.2.17.Final</hibernate.version>
</properties>
<dependencies>
<!-- JUNIT TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- SPRING CONTEXT -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- MYSQL DATABASE -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- DATABASE CONNECTION POOLING -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
If need more information, I can load more classes and console output. What could be wrong? any ideas?
Change to:
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(getSessionFactory());
return transactionManager;
}
or,
#Bean
public HibernateTransactionManager getTransactionManager(#Qualifier("getSessionFactory") SessionFactory sessionFactory) {
// your code here
}
or,
#Bean
public SessionFactory sessionFactory(DataSource dataSource) {
// your code here
}
There are few more ways.
Further Reading:
#Bean Methods in #Configuration Classes paragraph in Spring Framework javadoc of #Bean.
1.12.1. Basic Concepts: #Bean and #Configuration in Spring Framework Reference (version 5.1.3.RELEASE)

Error creating bean with Controller and entityManagerFactory

I create a project with Spring and when I compile I got this errors with Controller and entityManagerFactory. This is my first project with Spring and I don`t know what is wrong. Could you help me?
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeesController': Unsatisfied dependency expressed through field 'employeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository': Cannot create inner bean '(inner bean)#2996c83d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2996c83d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/pszymanski/config/DBConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: 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]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4921)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5231)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1805)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:506)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:405)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1595)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:280)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1184)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1412)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1380)
at java.lang.Thread.run(Thread.java:745)
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>pszymanski</groupId>
<artifactId>employees</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<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.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<!---Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.2.Final</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
Database Configuration:
#Configuration
#PropertySource(value = {"classpath:db.properties"})
#EnableJpaRepositories(basePackages = {"com.pszymanski.repository"})
public class DBConfig {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driver.class.name")); //hibernate configuration for database
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.user.name"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager() {
EntityManagerFactory factory = entityManagerFactory();
return new JpaTransactionManager(factory);
}
#Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(Boolean.TRUE);
vendorAdapter.setShowSql(Boolean.TRUE);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.pszymanski.model");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory.getObject();
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
EmployeeController:
package com.pszymanski.controller;
import com.pszymanski.model.Employee;
import com.pszymanski.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
import java.util.List;
#Controller
public class EmployeesController {
#Autowired
private EmployeeRepository employeeRepository;
#RequestMapping(value = "/employees", method = RequestMethod.GET)
public String getEmployeesPage(Model model) {
List<Employee> employeeList = employeeRepository.findAll();
model.addAttribute("employeesList", employeeList);
return "employees";
}
#RequestMapping(value = "/employees-add", method = RequestMethod.GET)
public String addEmployee(Model model) {
model.addAttribute("employees", new Employee());
return"employees-add";
}
#RequestMapping(value = "/employees-add/save", method = RequestMethod.POST)
public String saveEmployee( #ModelAttribute #Valid Employee employee, BindingResult result) {
if(result.hasErrors()) {
return "employees-add";
}
employeeRepository.save(employee);
return"redirect:/employees";
}
#RequestMapping(value = "/employees-add/cancel", method = RequestMethod.GET)
public String cancel() {
return "redirect:/employees";
}
#RequestMapping(value = "/employees/edit/{id}", method = RequestMethod.GET)
public String editEmployee(#PathVariable Long id, Model model){
Employee employee = employeeRepository.findOne(id);
model.addAttribute("employee", employee);
return "employee-add";
}
#RequestMapping(value ="/employees/delete/{id}", method = RequestMethod.POST)
public String deleteEmployee(#PathVariable Long id) {
employeeRepository.delete(id);
return "redirect:/employees";
}
}
EmployeeRepository:
package com.pszymanski.repository;
import com.pszymanski.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
}
See this article for an example. You are returning an EntityManagerFactory in your java config rather than the LocalContainerEntityManagerFactoryBean.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
Just return the factory, not factory.getObject().

Spring Boot war fails on startup in Elastic Beanstalk, but starts correctly when run locally

the same war file that runs without issue locally fails with the following looping error:
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'customSuccessHandler': Error creating bean with name 'customSuccessHandler': Unsatisfied dependency expressed through field 'engineerService': Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customSuccessHandler': Unsatisfied dependency expressed through field 'engineerService': Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:535) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.web.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:150) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.web.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:130) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.web.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:86) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169) [spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303) [catalina.jar:8.0.43]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) [catalina.jar:8.0.43]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) [catalina.jar:8.0.43]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729) [catalina.jar:8.0.43]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) [catalina.jar:8.0.43]
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1092) [catalina.jar:8.0.43]
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1834) [catalina.jar:8.0.43]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_121]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'customSuccessHandler': Error creating bean with name 'customSuccessHandler': Unsatisfied dependency expressed through field 'engineerService': Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customSuccessHandler': Unsatisfied dependency expressed through field 'engineerService': Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'engineerServiceImpl': Unsatisfied dependency expressed through field 'engineerRepository': Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'engineerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class mvc.domain.Engineer
looks like our CustomSuccessHandler -> Autowires a #Service -> which in turn wires a repository made of a JPA entity. It seems that it does not like the JPA Entity. Where I'm stuck is that the same war file will load without error when run locally.
In the past I have been able to switch dependency versions in the pom and it will resolve the issue. this has been very flaky and I can't seem to find a repeatable pattern
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.astontech.timecards</groupId>
<artifactId>com.astontech.timecards</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<!--<relativePath />-->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- ===================================================== -->
<!-- SPRING BOOT MODULES [DATA, WEB, SECURITY, TEST, REST] -->
<!-- ===================================================== -->
<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.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!--<scope>test</scope>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<!-- ============================================== -->
<!-- ============================================== -->
<!-- DATABASE DEPENDENCIES -->
<!-- ============================================== -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- ============================================== -->
<!-- ============================================== -->
<!-- TAG LIBRARIES [JSTL, JASPER, SPRING SECURITY] -->
<!-- ============================================== -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.security</groupId>-->
<!--<artifactId>spring-security-taglibs</artifactId>-->
<!--<version>4.0.3.RELEASE</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework.security</groupId>-->
<!--<artifactId>spring-security-ldap</artifactId>-->
<!--<version>4.0.3.RELEASE</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.security.extensions</groupId>
<artifactId>spring-security-saml2-core</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<!--<dependency>-->
<!--<groupId>org.slf4j</groupId>-->
<!--<artifactId>slf4j-log4j12</artifactId>-->
<!--<version>1.6.3</version>-->
<!--<scope>compile</scope>-->
<!--</dependency>-->
<!-- ============================================== -->
<!-- ============================================== -->
<!-- WEB JARS [BOOTSTRAP CSS, JQUERY] -->
<!-- ============================================== -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery-ui</artifactId>
<version>1.10.3</version>
</dependency>
<!-- ============================================== -->
<!--Quartz is a batch scheduler-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
<!-- ============================================== -->
<!-- SWAGGER API DOCUMENTATION -->
<!-- ============================================== -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<!-- ============================================== -->
<!-- CRM INTEGRATION-->
<!-- ============================================== -->
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>adal4j</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
<version>4.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.astontech.global.notification</groupId>
<artifactId>global.notification</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.astontech.global.integration.crm</groupId>
<artifactId>global.integration.crm</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
<distributionManagement>
<repository>
<id>central</id>
<name>artifactory.astontech.com-releases</name>
<url>http://artifactory.astontech.com:8081/artifactory/libs-release-local</url>
</repository>
</distributionManagement>
Application.java
package mvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class Application extends SpringBootServletInitializer
{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
CustomSuccessHandler.java
package mvc.configuration;
import mvc.common.LogHelper;
import mvc.domain.Engineer;
import mvc.services.EngineerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
#Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Autowired
EngineerService engineerService;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
protected void handle(HttpServletRequest request, HttpServletResponse response,
Authentication authentication)
throws IOException {
HttpSession session = request.getSession();
System.out.println("CustomSuccessHandler - handle()");
String targetUrl = determineTargetUrl(authentication, session);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/*
This method extracts the roles of the currently logged-in user and returns
appropriate URL according to their role
ROLES: Timecard Admin
Timecard Billing
Timecard Engineer
Timecard Superuser
*/
protected String determineTargetUrl(Authentication authentication, HttpSession session) throws IOException{
String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority grantedAuthority : authorities) {
roles.add(grantedAuthority.getAuthority());
}
LogHelper.viewMaster(true, false, "USER ROLES", roles);
if (isTimecardAdmin(roles)) {
LogHelper.viewMaster(true, "User has role: PAYROLL", "i");
session.setAttribute("userRole", "PAYROLL");
session.setAttribute("username", authentication.getName());
url = "/payroll";
}
else if (isTimecardBilling(roles)) {
LogHelper.viewMaster(true, "User has role: BILLING", "i");
url = "/billing";
}
else if (isTimecardEngineer(roles)) {
// ADD GENERAL ROLE OF "ENGINEER"
LogHelper.viewMaster(true, "User has role: ENGINEER", "i");
session.setAttribute("userRole", "ENGINEER");
// RETRIEVE ENGINEER DETAILS FROM DB & CRM
setCrmEngineer(session, authentication);
// REDIRECT
url = "/engineer";
}
else if (isTimecardSuperuser(roles)) {
LogHelper.viewMaster(true, "User has role: SUPER USER", "i");
session.setAttribute("userRole", "SUPER_USER");
url = "/super_user";
}
else {
url = "/accessDenied"; //todo: create an "/accessDenied" controller/view
}
return url;
}
private boolean isTimecardAdmin(List<String> roles) {
return (roles.contains("Timecard Admin") ||
roles.contains("ROLE_Timecard Admin") ||
roles.contains("ROLE_PAYROLL"));
}
private boolean isTimecardBilling(List<String> roles) {
return (roles.contains("Timecard Billing"));
}
private boolean isTimecardEngineer(List<String> roles) {
return (roles.contains("Field Engineer - Cisco") ||
roles.contains("Field Engineer - Dev") ||
roles.contains("ROLE_Field Engineer - Dev"));
}
private boolean isTimecardSuperuser(List<String> roles) {
return (roles.contains("Timecard Superuser") || roles.contains("ROLE_SUPER_USER"));
}
private void setCrmEngineer(HttpSession session, Authentication authentication) throws IOException{
//GET USERNAME BASED ON SPRING SECURITY METHOD
String username = authentication.getName();
LogHelper.viewMaster(true, true, "CRM ENGINEER:", username);
//SET USERNAME IN SESSION
session.setAttribute("username", username);
// CALL ENGINEER SERVICE TO RETRIEVE ENGINEER
Engineer loggedInEngineer = engineerService.getLoggedInEngineer(username);
// SET THAT INTO SESSION "loggedInEngineer"
session.setAttribute("loggedInEngineer", loggedInEngineer);
}
}
the EngineerService & Concrete Implementation are a bit extensive, and i can post them if they are requested.
EngineerRepository.java
package mvc.repositories;
import mvc.domain.Engineer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface EngineerRepository extends CrudRepository<Engineer, Integer> {
#Query("SELECT a from Engineer a where a.username = ?1")
Engineer findByUsername(String username);
#Query("SELECT COUNT(u) FROM Timecard u WHERE u.engineer.id=?1 AND u.isOnTime =false ")
int findTimeCardLateCount(Integer engineerId);
#Query("select a from Engineer a where a.isTrainee = ?1")
Iterable<Engineer> findByIsTrainee(boolean isTrainee);
}
Engineer.java
package mvc.domain;
import javax.persistence.*;
#Entity
public class Engineer {
//region PROPERTIES
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
Boolean isOverTimeEligible = false;
Boolean isPtoEligible = false;
Boolean isTrainee = false;
private String adpId;
private String technology;
private String username;
#OneToOne (cascade = CascadeType.ALL, fetch = FetchType.EAGER)
CrmEngineer crmEngineer;
//region CONSTRUCTORS
public Engineer() {}
public Engineer(CrmEngineer crmEngineer) {
this.crmEngineer = crmEngineer;
this.username = crmEngineer.getAston_astonemailaddress().split("#")[0];
}
//endregion
public Engineer(String username) {
this.username = username;
}
public String getAdpId() {
return adpId;
}
public void setAdpId(String adpId) {
this.adpId = adpId;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Boolean getIsOverTimeEligible() {
return isOverTimeEligible;
}
public void setIsOverTimeEligible(Boolean isOverTimeEligible) {
this.isOverTimeEligible = isOverTimeEligible;
}
public Boolean getIsPtoEligible() {
return isPtoEligible;
}
public void setIsPtoEligible(Boolean isPtoEligible) {
this.isPtoEligible = isPtoEligible;
}
public CrmEngineer getCrmEngineer() {
return crmEngineer;
}
public void setCrmEngineer(CrmEngineer crmEngineer) {
this.crmEngineer = crmEngineer;
}
public Boolean getIsTrainee() {
return isTrainee;
}
public void setIsTrainee(Boolean isTrainee) {
this.isTrainee = isTrainee;
}
}
I am able to reproduce this consistently using:
$ eb deploy
But i can get the same war file to load without issue if i goto the gui web console and redeploy the same war from Application Versions.
I am going to guess that this is some sort of error with the Elastic Beanstalk Agent when the war is deployed up via the python eb cli tools.
Elastic Beanstalk version:
64bit Amazon Linux 2017.03 v2.6.1 running Tomcat 8 Java 8
eb cli version:
EB CLI 3.10.1 (Python 3.6.0)
I'll keep jiggling the handle via the web gui when I deploy, and consider this resolved. However if anyone else has run across this and has a better workaround I'd love to hear it.
-cheers

Categories

Resources