Error while integrating spring with hibernate - java

I'm trying to integrate spring with hibernate but i get this error:
[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.
Here are some files:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.boraji.tutorial.spring</groupId>
<artifactId>spring-mvc-hibernate-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- Hibernate-C3P0 Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.4-Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-alpha2</version>
</dependency>
</dependencies>
</project>
Initializer:
public class MyWebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
application config:
#Configuration
#PropertySource("classpath:db.properties")
#EnableTransactionManagement
#ComponentScans(value = { #ComponentScan("com.boraji.tutorial.spring.dao"),
#ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
Properties props = new Properties();
// Setting JDBC properties
props.put(DRIVER, env.getProperty("mysql.driver"));
props.put(URL, env.getProperty("mysql.url"));
props.put(USER, env.getProperty("mysql.user"));
props.put(PASS, env.getProperty("mysql.password"));
// Setting Hibernate properties
props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
props.put(DIALECT, env.getProperty("hibernate.dialect"));
// Setting C3P0 properties
props.put(C3P0_MIN_SIZE,
env.getProperty("hibernate.c3p0.min_size"));
props.put(C3P0_MAX_SIZE,
env.getProperty("hibernate.c3p0.max_size"));
props.put(C3P0_ACQUIRE_INCREMENT,
env.getProperty("hibernate.c3p0.acquire_increment"));
props.put(C3P0_TIMEOUT,
env.getProperty("hibernate.c3p0.timeout"));
props.put(C3P0_MAX_STATEMENTS,
env.getProperty("hibernate.c3p0.max_statements"));
factoryBean.setHibernateProperties(props);
factoryBean.setAnnotatedClasses(User.class);
return factoryBean;
}
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
}
db.properties:
# MySQL properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/test
mysql.user=root
mysql.password=root
# Hibernate propert[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.ies
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect
#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
UserDao:
#Repository
public class UserDaoImp implements UserDao {
#Autowired
private SessionFactory sessionFactory;
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
public List<User> list() {
#SuppressWarnings("unchecked")
TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User");
return query.getResultList();
}
}
I saw lots of similar problems here but it didn't help. What could go wrong in my application?

DRIVER, URL, USER and PASS are all static fields. Make sure you imported all of them. Plus, make sure you imported the spring Environment (not the hibernate).
import static org.hibernate.cfg.Environment.*;
import org.springframework.core.env.Environment;

Related

#Value didn't work in my springboot project

I have a trouble in using #Value to inject the value in 'appliction.properties'. I created a new SpringBoot project, and profiled some properties in 'application.properties' file. But the application cannot start because of the 'dataSource' bean not created successfully. After debuging, i found the properties in 'application.properties' not load as expected.
Config class
#Configuration
public class SpringConfiguration {
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.driverClassName}")
private String driverClassName;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Bean("dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.driverClassName(driverClassName)
.url(url)
.username(username)
.password(password)
.build();
}
#Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
application.properties
spring.data.mongodb.uri=mongodb://localhost.27017
spring.data.mongodb.database=test
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.password=123
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://localhost:3306/common_test
part of stacktrace
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/ty/SpringConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.8.jar:5.3.8]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.8.jar:5.3.8]
... 102 common frames omitted
Caused by: java.lang.NullPointerException: null
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:325) ~[na:1.8.0_191]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_191]
at com.zaxxer.hikari.HikariConfig.attemptFromContextLoader(HikariConfig.java:970) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.HikariConfig.setDriverClassName(HikariConfig.java:480) ~[HikariCP-4.0.3.jar:na]
at org.springframework.boot.jdbc.DataSourceBuilder$MappedDataSourceProperty.set(DataSourceBuilder.java:460) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.jdbc.DataSourceBuilder$MappedDataSourceProperties.set(DataSourceBuilder.java:355) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.jdbc.DataSourceBuilder.build(DataSourceBuilder.java:190) ~[spring-boot-2.5.1.jar:2.5.1]
at com.ty.SpringConfiguration.dataSource(SpringConfiguration.java:35) ~[classes/:na]
debug scene
application.properties
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ty</groupId>
<artifactId>common-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>common-test</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
ok First of all this is not the issue with #Value annotation. If you are already using #ConfigurationProperties(prefix = "spring.datasource") then you don't need to use the #Value annotation. Ii will automatically configure all the properties for you.
You can create the datasource bean simply like this. Make sure you have required dependency in you pom.xml.
#Bean("mysqldataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
Add this annotation #PropertySource(value = "application.properties")
#Configuration
#PropertySource(value = "application.properties")
public class SpringConfiguration {
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.driverClassName}")
private String driverClassName;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Bean("dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.driverClassName(driverClassName)
.url(url)
.username(username)
.password(password)
.build();
}
#Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}

"Missing ServletContext" in CometD configuration (version 3.1.2) using Spring Boot Web Application (version 1.5.4)

Everything works fine when using the primer described in the CometD Reference Book. The versions of Spring, CometD and Jetty harmonizing together.
Now, I (a spring boot newbie) want to setup a Spring Boot Web Application (version 1.5.4) with CometD (version 3.1.2). And I also want to do the configuration via annotations without web.xml as mentioned here.
For that I found the github project "Livechat" which provides an "Example how to prepare the WebsocketConfiguration" for CometD in a Spring Boot project - I wasn't able to get it running.
All my attempts failed to get a simple spring boot application running with an annotated CometD configuration.
So, I ask for help, to setup a Spring Boot Application:
based on version 1.5.4
CometD (version 3.1.2)
Working on both: jetty 9.x and tomcat (if possible)
Using annotations instead of web.xml
Here is the main exception I got during my tests: Missing ServletContext
Caused by: java.lang.IllegalArgumentException: Missing ServletContext
at org.cometd.websocket.server.WebSocketTransport.init(WebSocketTransport.java:60) ~[cometd-java-websocket-javax-server-3.1.2.jar:na]
at org.cometd.server.BayeuxServerImpl.initializeServerTransports(BayeuxServerImpl.java:255) ~[cometd-java-server-3.1.2.jar:na]
at org.cometd.server.BayeuxServerImpl.doStart(BayeuxServerImpl.java:135) ~[cometd-java-server-3.1.2.jar:na]
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) ~[jetty-util-9.4.6.v20170531.jar:9.4.6.v20170531]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1758) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1695) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 29 common frames omitted
WebApplication.java:
#ComponentScan
#SpringBootApplication
#EnableScheduling
public class WebApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApplication.class, args);
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
}
}
CometDConfiguration.java (as described in the "CometD Reference Book" chapter "9.3.3.26. Annotation Based Spring Configuration":
#Component
public class CometDConfiguration implements DestructionAwareBeanPostProcessor, ServletContextAware {
private BayeuxServer bayeuxServer;
private ServerAnnotationProcessor processor;
#Inject
private void setBayeuxServer(BayeuxServer bayeuxServer) {
this.bayeuxServer = bayeuxServer;
}
#PostConstruct
private void init() {
this.processor = new ServerAnnotationProcessor(bayeuxServer);
}
#Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
processor.processDependencies(bean);
processor.processConfigurations(bean);
processor.processCallbacks(bean);
return bean;
}
#Override
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
return bean;
}
#Override
public boolean requiresDestruction(Object bean) {
return true;
}
#Override
public void postProcessBeforeDestruction(Object bean, String name) throws BeansException {
processor.deprocessCallbacks(bean);
}
#Bean(initMethod = "start", destroyMethod = "stop")
public BayeuxServer bayeuxServer() {
BayeuxServerImpl bean = new BayeuxServerImpl();
// bean.setOption(BayeuxServerImpl.LOG_LEVEL, "3");
return bean;
}
#Override
public void setServletContext(ServletContext servletContext) {
servletContext.setAttribute(BayeuxServer.ATTRIBUTE, bayeuxServer);
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<cometd-version>3.1.2</cometd-version>
<jetty-version>9.4.6.v20170531</jetty-version>
</properties>
<dependencies>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- JSP and JSTL SUPPORT -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
<!-- Cometd dependencies -->
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>bayeux-api</artifactId>
<version>${cometd-version}</version>
</dependency>
<dependency>
<groupId>org.cometd.javascript</groupId>
<artifactId>cometd-javascript-jquery</artifactId>
<version>${cometd-version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>cometd-java-server</artifactId>
<version>${cometd-version}</version>
</dependency>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>cometd-java-websocket-javax-server</artifactId>
<version>${cometd-version}</version>
</dependency>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>cometd-java-annotations</artifactId>
<version>${cometd-version}</version>
</dependency>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>cometd-java-oort</artifactId>
<version>${cometd-version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>${jetty-version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util-ajax</artifactId>
<version>${jetty-version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>apache-jstl</artifactId>
<version>${jetty-version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>apache-jsp</artifactId>
<version>${jetty-version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webAppConfig>
<contextPath>/cometd-primer</contextPath>
</webAppConfig>
</configuration>
</plugin>
</plugins>
</build>
</project>

Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container;

I am getting this error when i run my spring application:
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:124)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at com.dh.test.Application.main(Application.java:13)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:174)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:147)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:121)
... 7 more
My Main Class looks like:
#Configuration
#ComponentScan
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I am trying to configure the properties of spring through java classes using #Bean:
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "customerEntityManager",
transactionManagerRef = "customerTransactionManager",
basePackages = {"com.dh.test.repository.customer"})
public class CustomerDbConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] {"com.dh.test.model.customer"});
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalJpaProperties());
em.setPersistenceUnitName("customers");
return em;
}
Properties additionalJpaProperties(){
Properties properties = new Properties();
properties.setProperty("hibernate.ddl-auto", "update");
properties.setProperty("jdbc.dialect", "org.hibernate.dialect.MySQLDialect");
properties.setProperty("hibernate.show-sql", "true");
return properties;
}
#Bean
public DataSource dataSource(){
return DataSourceBuilder.create()
.url("jdbc:mysql://localhost:3306/customer")
.driverClassName("com.mysql.jdbc.Driver")
.username("root")
.password("root")
.build();
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory customerEntityManager){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(customerEntityManager);
return transactionManager;
}
}
extract of my POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>boot-multidb-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>boot-multidb-sample</name>
<description>Spring Boot Multiple Database Configuration</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- Datasource and connection pool dependencies -->
<!-- <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId>
</dependency> -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.33</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Can anyone please give a possible solution to fix this error, I tried checking the dependency hirerachy and the dependencies in my project.
It seems to me that the EmbeddedServletContainerFactory bean is not initialized. You need to kick it off:
Add the #SpringBootApplication annotation to your Application class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
The #SpringBootApplication annotation contains
#Configuration
#ComponentScan
#EnableAutoConfiguration (this is the one that might fix your problem)
Also you might need to add spring-boot-starter-web dependency in your pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Sources:
Spring boot error :Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
in Your class named Application ( i.e in the class where you write SpringApplication.run("...") you have to import org.springframework.boot.autoconfigure.SpringBootApplication for the annotation #SpringBootApplication.
If you import import org.springframework.boot.SpringBootConfiguration then you will get that exception.

Trying to use my Service in 2 classes : org.springframework.beans.factory.BeanCreationException: Error creating bean with name

Trying to use my AccountService (#Service) in 2 classes getting me this Error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mz.springContextWorld.repositories.AccountRepository com.mz.springContextWorld.services.AccountService.accountRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountRepository': Cannot resolve reference to bean 'neo4jTemplate' while setting bean property 'neo4jTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.neo4j.config.Neo4jConfiguration#0': Cannot resolve reference to bean 'graphDatabaseService' while setting bean property 'graphDatabaseService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'graphDatabaseService': FactoryBean threw exception on object creation; nested exception is java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, /home/matthias/IdeaProjects/springContextWorld/target/neo4j-db-plain
here is my github repo: https://github.com/mzober/springContextWorld/tree/CollectorManager_ErrorBranch
and here is the use of my accountService:
#Autowired
AccountService accountService;
public LoginPanel() {
//errorline here
this.accountService=GuiFactory.getInstance().mainWindow().getAccountService();
init();
addComponents();
}
...
#Autowired
AccountService accountService;
public RegistryAndLoginListener() {
//no error here
accountService=GuiFactory.getInstance().mainWindow().getAccountService();
}
...getting the accountService from the context-configuration:
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="com.mz.springContextWorld.domain"/>
<context:component-scan base-package="com.mz.springContextWorld.repositories"/>
<context:component-scan base-package="com.mz.springContextWorld.gui.listener"/>
<context:component-scan base-package="com.mz.springContextWorld.gui.components"/>
<context:component-scan base-package="com.mz.springContextWorld.gui.creational"/>
<context:component-scan base-package="com.mz.springContextWorld.services"/>
<neo4j:config storeDirectory="target/neo4j-db-plain"
base-package="com.mz.springContextWorld.domain"/>
<neo4j:repositories base-package="com.mz.springContextWorld.repositories"/>
<tx:annotation-driven />
... load the configuration in MainWindow (of my demo-application of Spring-Data-Neo4j)
#Autowired
public AccountService accountService;
public MainWindow() {
super(PROJECTNAME);
context= new ClassPathXmlApplicationContext("spring/spring-config.xml");
accountService=(AccountService)context.getBean("accountService");
...
}
public AccountService getAccountService(){return this.accountService;}
the AccountService:
#Service
#Transactional
public class AccountService {
#Autowired
AccountRepository accountRepository;
public AccountService(){
}
#Transactional
public Iterable<Account> getAll() {
return accountRepository.findAll();
}...
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mz.springContextWorld</groupId>
<artifactId>springContextWorld</artifactId>
<packaging>jar</packaging>
<version>3.2.1.RELEASE</version>
<name>springContextWorld</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.7.RELEASE</spring.version>
<spring-data-neo4j.version>${project.version}</spring-data-neo4j.version>
<slf4j.version>1.7.5</slf4j.version>
<neo4j.version>2.1.5</neo4j.version>
<junit.version>4.11</junit.version>
</properties>
<repositories>
<repository>
<id>neo4j-release-repository</id>
<name>Neo4j Maven 2 release repository</name>
<url>http://m2.neo4j.org/releases</url>
</repository>
</repositories>
<dependencies>
<!--spring data-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<!--spring data end-->
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
<!--hibernate end-->
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-kernel</artifactId>
<version>${neo4j.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<!--test end-->
<!--Loading Related dependencies ...logging-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--logging end-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
... and i'm trying to set the txmode to proxy, and more but the error is still there...
ty for helping
Seems your neo4j db has failed to start. Check last log line : Error starting org.neo4j.kernel.EmbeddedGraphDatabase, /home/matthias/IdeaProjects/springContextWorld/target/neo4j-db-plain

Spring Bean Creation Exception

To understand what real problem in Spring is really needs well knowledge about structure. I am seaching about this issue for two days and cant find any solution. In my project, using Hibernate when I build it gives the error message below:
2013-01-17 06:28:50,251 INFO [org.hibernate.cfg.SettingsFactory] - Database ->
name : MySQL
version : 5.0.96-community-nt
major : 5
minor : 0
2013-01-17 06:28:50,251 INFO [org.hibernate.cfg.SettingsFactory] - Driver ->
name : MySQL-AB JDBC Driver
version : mysql-connector-java-5.1.12 ( Revision: ${bzr.revision-id} )
major : 5
minor : 1
2013-01-17 05:13:45,060 ERROR [org.springframework.web.context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blogController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'langService':
Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'langDao' defined in URL [jar:file:/C:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/NCFrameworkAdmin/WEB-INF/lib/NCFramework-0.0.1-SNAPSHOT.jar!/com/ns/commerce/framework/lang/dao/LangDaoImpl.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/admin-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Wrong column type in db.nc_alert_log for column alerted. Found: bit, expected: TINYINT(1) DEFAULT 0; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/admin-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Wrong column type in db.nc_alert_log for column alerted. Found: bit, expected: TINYINT(1) DEFAULT 0
The interesting thing is blogController, langServices and LangDao is related, however they have nothing about "nc_alert_log" table.
LangDaoImpl
package com.ns.commerce.framework.lang.dao;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.ns.commerce.framework.lang.model.Lang;
import com.ns.commerce.framework.generic.dao.GenericDAOImpl;
#Repository("langDao")
public class LangDaoImpl extends GenericDAOImpl<Lang, Long> implements LangDao {
#Autowired
public LangDaoImpl(#Qualifier("sessionFactory") SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
#Override
public Lang findByLocaleCode(String localeCode) {
Criteria criteria = getCriteria();
criteria.add(Restrictions.eq("localeCode", localeCode));
return findByCriteriaFirst(criteria);
}
#Override
public Lang findBySubdomain(String subdomain) {
Criteria criteria = getCriteria();
criteria.add(Restrictions.eq("subdomain", subdomain));
return findByCriteriaFirst(criteria);
}
#Override
public Lang findDefaultLang() {
Criteria criteria = getCriteria();
criteria.add(Restrictions.eq("defaultFlag", true));
return findByCriteriaFirst(criteria);
}
}
AlertLog.Java Model
#Column(name="alerted", columnDefinition = "TINYINT(1) DEFAULT 0")
private int alerted;
On the Database: Alerted Column > TINYINT(1) and deafult value is 0.
DB.properties
hibernate.hbm2ddl.auto=validate
#hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.import_files=/import_standard.sql
hibernate.show_sql=false
hibernate.format_sql=true
hibernate.generate_statistics=false
hibernate.use_sql_comments=true
hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory
hibernate.cache.use_second_level_cache=true
#-------------------------------------------------------------------------------
# MySQL Settings
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/asd?autoReconnect=true
jdbc.username=asd
jdbc.password=asd
# Property that determines which Hibernate dialect / MySQL5Dialect || MySQLDialect
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Pom.xml
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>NC_Core</artifactId>
<groupId>com.ns.commerce</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>NCFrameworkAdmin</artifactId>
<packaging>war</packaging>
<name>NCFrameworkAdmin Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.nc.commerce</groupId>
<artifactId>NCFramework</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Joda Time Library -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
<!--Regular Expression Libraries -->
<dependency>
<groupId>oro</groupId>
<artifactId>oro</artifactId>
</dependency>
<dependency>
<groupId>jakarta-regexp</groupId>
<artifactId>jakarta-regexp</artifactId>
</dependency>
<!-- Commons validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
</dependency>
<!-- Tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
</dependency>
<!-- AOP dependency -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
</dependency>
</dependencies>
<build>
<finalName>NCFrameworkAdmin</finalName>
If any other source needed please comment.
Wrong column type in db.nc_alert_log for column alerted.
Found: bit, expected: TINYINT(1) DEFAULT 0
Causing the issue. Check type of alerted column in database and make sure you are using the same in AlertLog.java.
nc_alert_log and LangDao are not directly related, but LangDao and the hibernate sessionFactory are. The sessionFactory cant be created because the database definition is wrong. The eror indicates the columntype in the database isn't TINYINT, but BIT (boolean). That's why the sessionFactory fails to start. Without a sesionFactory the LangDao can't be created etc etc.
private int alerted;
try changing to:
private boolean alerted;

Categories

Resources