Hibernate exception hibernate.cfg.xml not found - java

I'm trying to start project with Hibernate and Maven.
I got such exception:
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.
Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2176)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2157)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
at FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15)
Here is the screenshot of my project structure, (hibernate.cfg.xml is in src/):
http://imageshack.us/photo/my-images/692/screenshotxba.jpg/
CrudsOps.java
package FirstHibernate.com.myhib.CRUDS;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CrudsOps {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory sf = new Configuration().configure().buildSessionFactory();
System.out.println("Cfg and hbm files loaded succesfully");
Session session = sf.openSession();
session.beginTransaction();
System.out.println("Transaction began");
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>FirstHibernate</groupId>
<artifactId>com.myhib</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>com.myhib Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.8.Final</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
</dependencies>
<build>
<finalName>com.myhib</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
What could be a source of that exception?

As #JBNizet said, your hibernate.cfg.xml should be in src/main/resources. In src, it won't be added to your classpath for runtime.
If you are running your project within Eclipse, don't forget in the project preferences in the build path configuration to check that the src/main/resources is not excluded from your class path and is indeed a source folder.

The file should be in the runtime classpath. Maven copies to the target/classes folder the resources that are under src/main/resources. So your config file should be there.
That said, you don't show the code which loads the file, so there might be other problems.

You can load hibernate.cfg.xml from a different directory (not necessarily the classpath) using the configure(File configFile) method that takes the hibernateConfig File argument.
(note, am using hibernate 4.3.7)
Like this:
String hibernatePropsFilePath = "/etc/configs/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);
Configuration configuration = new Configuration();
configuration.configure(hibernatePropsFile);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

For the People who are facing this issue while deploying on linux machine
You need to copy hibernate.cfg.xml to classes directory of your war project.
In Eclipse/Maven Project: (During Development)
You need to copy hibernate.cfg.xml to src directory of your Eclipse/Maven project.

If you are working in Intellij Idea then make a folder named "resources" under src\main\java. Open Module setting of your project, select "Modules" from left and in the "sources" tab select the newly created "resources" folder and mark it as "Resources".
then this should work
Configuration con = new Configuration().configure("hibernate.cfg.xml");

If you are using Netbeans, put your hibernate.cfg.xml file into the "Build > classes >" directory and it will work.

Related

Error 404, when trying to show something in tomcat

I did everything in this video:
But when I'm typing:http://localhost:8080/spring-sample-1.0-SNAPSHOT/hello
This error shows up:
HTTP Status 404 – Not Found
Type Status Report
Message The requested resource [/spring-sample-1.0-SNAPSHOT/hello] is not available
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
The only thing I changed was in: tomcat/bin/setclasspath.bat, I added one line there:
set JRE_HOME=C:\Program Files\Java\jre1.8.0_271
Because without that the server does not start
Okey, so my application is really simple, i created mvn project in java 15, then two classes:
Config:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Configuration
#ComponentScan({"app"})
#EnableWebMvc
public class Config extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[0];
}
}
Hello:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Hello {
#GetMapping("/hello")
public String get(){
return "Bycza zagroda!";
}
}
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>pl.bykowski</groupId>
<artifactId>spring-sample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Then I packed everything in war file and add it in tomcat manager here: WAR file to deploy
After that I clicked /spring-sample-1.0-SNAPSHOT in tomcat module
and then typed hello at the end
Any ideas what is going wrong? :/
I found the issue: in Config class you provided incorrect values for servlet mapping and servlet config class.
Please change Config class as follows:
#Configuration
#ComponentScan({"app"})
#EnableWebMvc
public class Config extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {Config.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
First of all I recommend to setup JAVA_HOME or JRE_HOME env variable for OS.
For more details: https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html
In any case changing tomcat's files is not good idea :)
For solving issue with unreachable url please check:
for installed tomcat:
as rule, name of war file is context name and part of the url(spring-sample-1.0-SNAPSHOT), but that name can be configured in context.xml (Documentation: https://tomcat.apache.org/tomcat-8.0-doc/config/context.html)
open manager window as you can see in video (http://localhost:8080/manager/html) and find link of your web application
for embedded tomcat:
the context path should be like artifactId in pom.xml
#saver
Log from tomcat when deploying:
21-Dec-2020 16:49:22.227 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:\Users\Damian\Desktop\JAVA\apache-tomcat-8.5.61\webapps\spring-sample3-1.0-SNAPSHOT.war]
21-Dec-2020 16:49:24.113 INFO [http-nio-8000-exec-17] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21-Dec-2020 16:49:24.138 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:\Users\Damian\Desktop\JAVA\apache-tomcat-8.5.61\webapps\spring-sample3-1.0-SNAPSHOT.war] has finished in [1,907] ms
So which versions of JRE and JDK, Should I use?
#daniep kajoi you should set path on java 15 for tomcat, or change maven.compiler.source attribute in pom.xml on 1.8 version - one of two options.
And I see in yours log that yours path is 'spring-sample3-1.0-SNAPSHOT.war'
21-Dec-2020 16:49:22.227 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:\Users\Damian\Desktop\JAVA\apache-tomcat-8.5.61\webapps\spring-sample3-1.0-SNAPSHOT.war]
21-Dec-2020 16:49:24.113 INFO [http-nio-8000-exec-17] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21-Dec-2020 16:49:24.138 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:\Users\Damian\Desktop\JAVA\apache-tomcat-8.5.61\webapps\spring-sample3-1.0-SNAPSHOT.war] has finished in [1,907] ms
try to open url: http://localhost:8080/spring-sample3-1.0-SNAPSHOT.war/hello

Why jdbc driver is not found from generated jar? [duplicate]

This question already has answers here:
Whats the best way to bundle the whole project in Maven?
(3 answers)
Closed 4 years ago.
I have a JAVA SE project that works fine. The problem arises when I try to use it externally as a jar.
I'm using Eclipse Oxygen. My JAVA SE project, as you can see in my pom, uses JDBC4.2. Oracle doc states:
"In previous versions of JDBC, to obtain a connection, you first had
to initialize your JDBC driver by calling the method Class.forName."
Moreover:
Any JDBC 4.0 drivers that are found in your class path are
automatically loaded. (However, you must manually load any drivers
prior to JDBC 4.0 with the method Class.forName.)
For this reason, I do not need to write Class.forname(...) in DBConnection class (see below).
When I use DBConnection in my project, it works properly, but, if I create a jar and try to import it in another project, I get the following exception: "No suitable driver found for jdbc:postgresql://host:port/dbName". The following are the steps I do to create the jar:
mvn clean install
create new java project (TestProject) in a new empty clean workspace
create a test class with main
call a class that uses DBConnection from main
I have no compilation problem (all the classes from the jar are loaded correctly)
When I run the main, "getConnection" of my DBConnection class throws the following exception: "No suitable driver found for jdbc:postgresql://host:port/dbName"
If I right click on TestProject-> configure -> convert to maven project, then add postgres driver dependency, it all works fine!!!.
Shouldn't the PostgreSQL driver already be present in my jar? Why should I add it in the dependencies of the user project?
The following is the code of the class DBConnection:
package generic.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBConnection {
private static final String FILE_NAME = "db";
private static final String URL = "url";
private static final String USER = "user";
private static final String PASSWORD = "password";
private static Connection conn;
private DBConnection(){
}
public static synchronized Connection getConnection() throws SQLException, ClassNotFoundException, IOException {
if(DBConnection.conn == null || DBConnection.conn.isClosed()){
Properties props = PropertiesReader.readPropertyFile(FILE_NAME);
String url = props.getProperty(URL);
String user = props.getProperty(USER);
String password = props.getProperty(PASSWORD);
Connection conn = DriverManager.getConnection(url, user, password);
DBConnection.conn = conn;
}
return DBConnection.conn;
}
}
The following is my pom:
<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>groupid</groupId>
<artifactId>artifactid</artifactId>
<version>1.0</version>
<properties>
<skipTests>true</skipTests>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<skipTests>${skipTests}</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency>
</dependencies>
</project>
The default behaviour does not repackage dependend libraries into the created artifacts. Usually external libraries will not changed as often as your software does, and will be deployed to an application server.
With microservices e.g. spring-boot this has changed and you can deploy a single .jar file including all dependencies (even tomcat is included).
You have two options:
Put all libraries in a lib-folder and add it to the classpath.
Create a fat jar

Spring-boot jersey maven failed to run war file

We are creating a spring-boot jersey application.
Now we want to create executable war file.
The problem is the application runs fine when I run it with
mvn spring-boot:run
But when I try to package it to war and run it with java -jar ABD.war
its giving the following error
Caused by: java.io.FileNotFoundException: /Users/ABC/ABD-0.0.1-SNAPSHOT.war!/WEB-INF/classes (No such file or directory)
Caused by: org.glassfish.jersey.server.internal.scanning.ResourceFinderException:
Here are the part of pom.xml I'm using ,
<packaging>war</packaging>
.
.
.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.slf4j.version>1.7.7</org.slf4j.version>
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<java.version>1.8</java.version>
</properties>
.
.
.
.
.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Although when I unpack the war file I can see the WEB-INF/classes folder is there.
OK found the solution.
I have a jersery config class, where I added all of controllers class with packages().
When I commented it out and change it to register("controller.class") It started to work!
#Configuration
#ApplicationPath("/path")
#Controller
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(MultiPartFeature.class);
register(OneController.class);
//packages("com.controllers");
}
}
#
Update
#
private static final Logger logger = LoggerFactory.getLogger(OneController.class);
public JerseyConfig() {
scan("com.somepackages");
}
public void scan(String... packages) {
for (String pack : packages) {
Reflections reflections = new Reflections(pack);
reflections.getTypesAnnotatedWith(Path.class)
.parallelStream()
.forEach((clazz) -> {
logger.info("New resource registered: " + clazz.getName());
register(clazz);
});
}
}
#
With this solution you can get all controllers in jersey register through package scan.

Spring-Boot Resource Not Found when using executeable Jar

again I face a strange issue and hope someone here can help.
I have a spring boot backend module, what works in eclipse well and application is executeable when starting main in application.java. Everything fine.
My application makes import of example data to database using csv-files what is included in src/main/resources folder. As mentioned, when starting in eclipse everything works.
Now I would like to execute it as executable jar, the application begins to start and then it failed to start, because it cannot find the csv files. The path what it prints out, where it looked for the files, is correct and the csv files are in the jar included.
The Pom of the module looks like follows:
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>at.company.bbsng</groupId>
<artifactId>bbsng-import</artifactId>
<version>0.1.0-SNAPSHOT</version>
</parent>
<artifactId>bbsng-import-backend</artifactId>
<name>bbsng-import-backend</name>
<properties>
<start-class>at.company.bbsng.dataimport.Application</start-class>
</properties>
<dependencies>
<!-- SPRING ... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
<!-- EXCLUDE LOGBACK AND USE LOG4J -->
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- COMMONS ... -->
...
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Path to csv-files are configured in propery files as follows:
# EXAMPLE PATH
csv.path=config/csv/
The part of java config file is as follows:
...
#Value("${csv.path}")
private String csvExamplePath;
#Bean
public Resource addressResource() {
return new ClassPathResource(csvExamplePath + CSV_ADDRESS);
}
...
In the jar the files are located at path
\config\csv\
Stacktrace:
Caused by: java.io.FileNotFoundException: class path resource [config/csv/Company.csv] cannot be resolved to absolute file path because it does not reside in th
e file system: jar:file:/C:/Development/Projekte/bbsng/trunk/import/backend/target/bbsng-import-backend-0.1.0-SNAPSHOT.jar!/config/csv/Company.csv
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:207)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52)
at at.compax.bbsng.dataimport.app.source.company.CompanyGenerator.init(CompanyGenerator.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java
Again, the application works as expected when starting it from eclipse, only executable jar complains about missing csv-files, what are in jar already.
Any clue would be great.
Okay, already I found the real problem and the solution.
First, the application use the correct path to the csv files, but there is another issue when using an executable jar what I found under following link. Stackoverflow-Link
Before I come to issue with executable jar I used following solution for getting CSV-File (Issue is getFile()):
final List<String> resourceLines = FileReadUtils.readLines(specialisationResource.getFile());
for (final String line : resourceLines) {
data.add(getNewTransientSpecialisation(line));
}
But in executeable jar I cant use my resource as file, I need to use it as stream, see provided link above. So I needed to change my code. If you prefer using native java, you can do follows:
final InputStream inputStream = specialisationResource.getInputStream();
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
data.add(getNewTransientSpecialisation(line));
}
I prefer using frameworks and use apache commons like follows:
final List<String> resourceLines = IOUtils.readLines(specialisationResource.getInputStream());
for (final String line : resourceLines) {
data.add(getNewTransientSpecialisation(line));
}
So just remember, don't use File() for getting resource, always use stream do avoid that issue from beginning :-)
Hope that helps someone.
I encountered this limitation too and created this library to overcome the issue: spring-boot-jar-resources
It basically allows you to register a custom ResourceLoader with Spring Boot that extracts the classpath resources from the JAR as needed, transparently:
new SpringApplicationBuilder()
.sources(Application.class)
.resourceLoader(new JarResourceLoader())
.run(args);
With that ResourceLoader you can do resource.getFile() on any classpath resource.
Now I needed to find xmlFiles into a resource folder from a JAR and facing similar problems described here already. I would like to share my findings and how I got it work, maybe it is helpful.
In a jar I have "db-input" folder under src/main/resources with any number for xml-Files for DB-Input. My application is Spring-Based:
#Component
public class DatabaseInitializer implements InitializingBean {
#Autowired DomainConfigurationRepository repository;
#Autowired MarshallerService marshallerService;
#Autowired ApplicationContext context;
#Override
public void afterPropertiesSet() throws Exception {
final Resource[] resources = context.getResources("classpath*:db-input/*");
final Set<String> filePaths = findInputFileNames(resources);
final Set<DomainConfiguration> configurations = createConfigurations(filePaths);
repository.save(configurations);
}
private Set<DomainConfiguration> createConfigurations(final Set<String> filePaths) throws Exception {
final Set<DomainConfiguration> configurations = new HashSet<>();
for(final String path : filePaths){
final Resource resource = context.getResource(path);
final DomainConfigurationXO xoConfiguration = marshallerService.unmarshal(resource.getInputStream());
final DomainConfiguration configuration = PopulationUtils.getPopulatedConfiguration(xoConfiguration);
configurations.add(configuration);
}
return configurations;
}
public Set<String> findInputFileNames(final Resource[] inputDirectoryResources) throws IOException {
return Arrays.stream(inputDirectoryResources)
.map(resource -> extractURI(resource))
.collect(Collectors.toSet());
}
private String extractURI(Resource resource){
try {
return resource.getURI().toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Cannot load configuration class

I am following this tutorial about how to use Spring and based on the provided example, I get the following exception:
Exception in thread "main" java.lang.IllegalStateException: Cannot load configuration class: com.tutorialspoint.HelloWorldConfig
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:378)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:263)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:126)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at com.tutorialspoint.MainApp.main(MainApp.java:9)
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:237)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:128)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:100)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:368)
... 7 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:384)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:219)
... 12 more
Caused by: java.lang.SecurityException: class "com.tutorialspoint.HelloWorldConfig$$EnhancerBySpringCGLIB$$b5aece24"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(ClassLoader.java:952)
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:666)
at java.lang.ClassLoader.defineClass(ClassLoader.java:794)
... 18 more
I have researched my problem and have found this; someone also has had the same problem as me, and it has something to do with ensuring that ASM is compatible with CGLIB. However I have tried this solution and it has not worked, I even went as far as using the exact same versions as the one provided (GBLIB 2.2.2 and ASM 3.3.1).
What do I need to do in order to correct this?
For simplicity, here are the files which I am using that were extracted from the provided tutorial.
HelloWorldConfig.java
package com.tutorialspoint;
import org.springframework.context.annotation.*;
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld() {
return new HelloWorld();
}
}
HelloWorld.java
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
}
MainApp.java
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
public class MainApp {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext ctx = new AnnotationConfigApplicationContext(
HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
}
Also by saying 'However I have tried this solution and it has not worked' I mean that the exact same error is returned.
I had the same problem and realized the JRE version I have in the POM.xml or the default one associated with the project was not set in the class path. So updated the same under Preferences -> Installed JREs and ran the application it worked.
Gone through this problem yesterday and
Here is the solution.
Open Eclipse
Open window in menu bar -> preferences -> java ->installed jre
add new jre which is installed in system(c:program_files->java->jre->bin) add it.
Select the new added jre and BOOOM 🔥🔥
This problem occurred due to spring dependency problem, I too used below dependency facing same issue, the configuration classes didn't loaded
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
Try below one: for me it is working
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
So, i would say the "other" you mentioned, has an different problem.
Even when the "Last-Shown-Exception" is the same as yours.
But as you can see in your stacktrace, the "source" is a SecurityException.
The *Cannot load configuration class*-Error is a aftereffect
I assume there is something wrong with the "code signation" in your project
or, due to ByteCode-Manipulation, the signation is broken.
PS:
Sometimes this also can happen, when you reference "SignedLibs" and "UnsignedLibs" in your project.
in this case remove the signation from the signed libs.
All jars required for this project to run:
1) org.springframework.core-3.0.1.RELEASE-A.jar
2) spring-context-3.0.4.RELEASE.jar
3) org.springframework.beans-3.0.1.RELEASE-A.jar
4) commons-logging-1.1.1.jar
5) asm-3.3.1.jar
6) cglib-2.2.2.jar
To get these jars,either add the downloaded jars to your project directly, or provide the following dependencies in the pom.xml to get them automatically downloaded for you.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
Add this to your maven settings.xml file if not already present:
<profiles>
<profile>
<id>SPRINGLEARN</id>
<activation>
<jdk>1.8</jdk>
</activation>
<repositories>
<repository>
<id>thirdPartyRepo</id>
<name>Third party repository</name>
<url>https://repo.spring.io/libs-release/</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>thirdPartyPluginRepo</id>
<name>Third party plugin repository</name>
<url>https://repo.spring.io/libs-release/</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
After this, just run your project.
-Right click on your project -> Run as -> Maven clean
-Right click on your project -> Run as -> Maven install
-Right click on your project -> Run as -> Java application
I too faced this issue.
Use the latest version of spring. works in versions of 5.
Check out the POM.xml for suitable dependencies
enter image description here
and also JRE as well... it will work with java 1.7

Categories

Resources