How to convert spring-boot-web-application to spring application - spring

I'm following this spring-data-aerospike tutorial and setup the sample application and it is working fine.
Now I want to convert this spring boot application to spring application so I wrote the below code.
package com.aerospike.demo.simplespringbootaerospikedemo;
import com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.aerospike.core.AerospikeTemplate;
public class TestSpringConfig {
public static void main(String[] args) throws IOException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AerospikeConfiguration.class);
AerospikeTemplate template = ctx.getBean(AerospikeTemplate.class);
}
}
18:33:25.430 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aerospikeTemplate' defined in com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration: Unsatisfied dependency expressed through method 'aerospikeTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'aerospikeClient' defined in com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.aerospike.client.AerospikeClient]: Factory method 'aerospikeClient' threw exception; nested exception is com.aerospike.client.AerospikeException$Connection: Error -8: Failed to connect to host(s):
null 0 Error -8: java.net.ConnectException: Can't assign requested address (connect failed)
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:917)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:582)
org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)
com.aerospike.demo.simplespringbootaerospikedemo.TestSpringConfig.main(TestSpringConfig.java:10)
So I did tweak the code liitle bit like below to set the properties into system -
import com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.aerospike.core.AerospikeTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.stream.Stream;
public class TestSpringConfig {
public static void main(String[] args) throws IOException {
System.out.println(ClassLoader.getSystemResourceAsStream("application.properties").available());
Properties props = new Properties();
InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream("application.properties");
if (resourceAsStream != null) {
props.load(resourceAsStream);
}
if(props != null) {
System.setProperties(props);
}
try {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AerospikeConfiguration.class);
AerospikeTemplate template = ctx.getBean(AerospikeTemplate.class);
} catch (Exception e) {
StackTraceElement[] st = e.getStackTrace();
if(st != null) {
System.out.println("st.length = " + st.length);
}
Stream.of(st).forEach(System.out::println);
} catch (ExceptionInInitializerError e) {
System.out.println(e.getCause());
e.getCause().printStackTrace();
}
}
}
When I run the program with the changes above I get the below stack trace for e.getCause().printStackTrace() -
java.lang.NullPointerException
at ch.qos.logback.core.CoreConstants.<clinit>(CoreConstants.java:47)
at ch.qos.logback.classic.layout.TTLLLayout.doLayout(TTLLLayout.java:52)
at ch.qos.logback.classic.layout.TTLLLayout.doLayout(TTLLLayout.java:23)
at ch.qos.logback.core.encoder.LayoutWrappingEncoder.encode(LayoutWrappingEncoder.java:115)
at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:230)
at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:102)
at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:84)
at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:51)
at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:270)
at ch.qos.logback.classic.Logger.callAppenders(Logger.java:257)
at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:421)
at ch.qos.logback.classic.Logger.filterAndLog_0_Or3Plus(Logger.java:383)
at ch.qos.logback.classic.Logger.log(Logger.java:765)
at org.apache.commons.logging.LogAdapter$Slf4jLocationAwareLog.debug(LogAdapter.java:468)
at org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:628)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)
at com.aerospike.demo.simplespringbootaerospikedemo.TestSpringConfig.main(TestSpringConfig.java:26)
I'm running out of the the available options. How to fix this error.
The code is on github here

I added line.separator=\n to the application.properties which fixed the issue

Related

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException

package polymorphism;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class TVUser {
public static void main(String[] args) {
// 1.Spring 컨테이너를 구동한다.
AbstractApplicationContext factory =
new GenericXmlApplicationContext("applicationContext.xml");
// 2. Spring 컨테이너로 부터 필요한 객체를 요청(Lookup) 한다
TV tv = (TV)factory.getBean("tv");
tv.powerOn();
tv.volumeUp();
tv.volumeDown();
tv.powerOff();
// 3. Spring 컨테이너를 종료한다.
factory.close();
}
}
/BoardWeb/src/main/resources/log4j.xml
/BoardWeb/src/test/resources/log4j2.xml
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:224)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:195)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:257)
at org.springframework.context.support.GenericXmlApplicationContext.load(GenericXmlApplicationContext.java:130)
at org.springframework.context.support.GenericXmlApplicationContext.(GenericXmlApplicationContext.java:70)
at polymorphism.TVUser.main(TVUser.java:14)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:187)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:333)
... 8 more

Not able to persist Object in a table using Hibernate

I am consuming API with the help of Spring Boot and trying to persist the same in MySQL database by using Hibernate, but getting error doing so, I have tried things but somehow I am stuck with it.
Stack Trace
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.5.RELEASE)
2018-09-20 00:51:26 INFO com.diwakar.GroupBeema - Starting GroupBeema on LP-PC0MQFY6 with PID 13084 (started by diwakar_b in C:\Diwakar Playground\GroupBeema)
2018-09-20 00:51:26 INFO com.diwakar.GroupBeema - No active profile set, falling back to default profiles: default
2018-09-20 00:51:26 INFO o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#12d4bf7e: startup date [Thu Sep 20 00:51:26 IST 2018]; root of context hierarchy
2018-09-20 00:51:27 INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c2e2ffe4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-09-20 00:51:28 INFO o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
2018-09-20 00:51:28 INFO o.a.catalina.core.StandardService - Starting service [Tomcat]
2018-09-20 00:51:28 INFO o.a.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.5.34
2018-09-20 00:51:28 INFO o.a.c.core.AprLifecycleListener - The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_172\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_172/bin/server;C:/Program Files/Java/jre1.8.0_172/bin;C:/Program Files/Java/jre1.8.0_172/lib/amd64;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Windows\CCM;C:\Program Files\PuTTY\;C:\Program Files\Git\cmd;C:\Program Files\Gradle\gradle-4.5.1\bin;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Users\diwakar_b\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Docker Toolbox;C:\Users\diwakar_b\Downloads\eclipse-jee-photon-R-win32-x86_64\eclipse;;.]
2018-09-20 00:51:29 INFO o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2018-09-20 00:51:29 INFO o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 2997 ms
2018-09-20 00:51:29 INFO o.s.b.w.s.ServletRegistrationBean - Servlet dispatcherServlet mapped to [/]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
2018-09-20 00:51:29 WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hibernateUtil': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
2018-09-20 00:51:29 INFO o.a.catalina.core.StandardService - Stopping service [Tomcat]
2018-09-20 00:51:29 INFO o.s.b.a.l.ConditionEvaluationReportLoggingListener -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-20 00:51:29 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hibernateUtil': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265)
at com.diwakar.GroupBeema.main(GroupBeema.java:10)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:590)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
... 31 common frames omitted
Caused by: java.lang.NullPointerException: null
at com.diwakar.hibernate.HibernateUtil.getSessionfactory(HibernateUtil.java:19)
at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353.CGLIB$getSessionfactory$0(<generated>)
at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353$$FastClassBySpringCGLIB$$adc355b2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:365)
at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353.getSessionfactory(<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:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 32 common frames omitted
GroupBeema Class
package com.diwakar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class GroupBeema{
public static void main(String[] args) {
SpringApplication.run(GroupBeema.class, args);
}
}
InsurerController
package com.diwakar.insurer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.diwakar.hibernate.InsurerDao;
#RestController
public class InsurerController {
#Autowired
public InsurerService insurerService;
#Autowired
private InsurerDao insurerDao;
#RequestMapping("/insure")
public List<Insurer> getInsurersInfo() {
List<Insurer> list = insurerService.getAllInsurer();
//insurerService.createTable(list);
insurerDao.createInsurer(list);
return list;
}
}
InsurerService
package com.diwakar.insurer;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
#Service
public class InsurerService {
public List<Insurer> getAllInsurer( ) {
List<Insurer> list = new ArrayList<Insurer>();
try {
Client client = Client.create();
WebResource webResource = client.resource("https://termlife.policybazaar.com/api/v1/quotes");
String input = "//some json data"
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
JSONArray jsonArray = new JSONArray(output);
for(int n = 0; n < jsonArray.length(); n++) {
JSONObject obj = jsonArray.getJSONObject(n);
Insurer ins = new Insurer();
ins.setBasicPremium(obj.getInt("BasicPremium"));
ins.setE2EName(obj.getString("E2EName"));
ins.setE2ESupplier(obj.getString("E2ESupplier"));
list.add(ins);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
HibernateUtil
package com.diwakar.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class HibernateUtil {
#Autowired
private EntityManagerFactory entityManagerFactory;
#Bean
public SessionFactory getSessionfactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
//throw new NullPointerException("factory is not hibernate factory.!!");
System.out.println("Exception in getSessionfactory method..");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
InsurerDAO
package com.diwakar.hibernate;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.diwakar.insurer.Insurer;
#Repository
public class InsurerDao {
#Autowired
private SessionFactory sessionFactory;
public void createInsurer(List<Insurer> insurer) {
Session session = null;
//SessionFactory sessionFactory = null;
try {
//sessionFactory = new Configuration().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
Integer i = (Integer) session.save(insurer);
System.out.println("Insurer table is created with " + i + " records..!!");
session.getTransaction().commit();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Application properties
//assume everything is correct
The problem with your code is that SessionFactory is a subinterface to EntityManagerFactory. Even if you change that to EntityManager, it won't work as EntityManager is dependent on EntityManagerFactory and therefore, the method for it is called first in the lifecycle at startup. Could you please explain, why you need the SessionFactory? If you want to have the EntityManager, you can just inject that by using #PersistenceContext in your services.
You cannot autowire in a configuration class put pass your dependencies as parameters
So your HibernateUtil must look like:
#Configuration
public class HibernateUtil {
#Bean
public SessionFactory getSessionfactory(EntityManagerFactory entityManagerFactory) {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
//throw new NullPointerException("factory is not hibernate factory.!!");
System.out.println("Exception in getSessionfactory method..");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}

Error creating bean, Bean instantiation via factory method failed

am trying to configure elasticsearch in Spring boot but Bean instantiation is failing, Node Builder has been removed from elasticsearch api so am trying to use Settings.Builder but its not helping
below is the code:
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.demo.elastic.elasticdemo.repository")
public class ElasticConfiguration {
#SuppressWarnings("resource")
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws IOException {
File tempDir = File.createTempFile("temp-elastic", Long.toString(System.nanoTime()));
System.out.println("Temp directory: "+ tempDir.getAbsolutePath());
Settings.Builder settings = Settings.builder()
//http settings
.put("http.enable", "true")
.put("http.cor.enable", "true")
.put("http.cors.allow-origin", "https?:?/?/localhost(:[0-9]+)?/")
.put("http.port", "9200")
//transport settings
.put("transport.tcp.port", "9300")
.put("network.host", "localhost")
//node settings
.put("node.data", "true")
.put("node.master", "true")
//configuring index
.put("index.number_of_shards", "1")
.put("index.number_of_replicas", "2")
.put("index.refresh_interval", "10s")
.put("index.max_results_window", "100")
//configuring paths
.put("path.logs", new File (tempDir, "logs").getAbsolutePath())
.put("path.data", new File (tempDir, "data").getAbsolutePath())
.put("path.home", tempDir);
//.build();
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
return new ElasticsearchTemplate(client);
}
}
what am i doing wrong.??
error am getting:
2018-09-27 19:23:35.825 ERROR 57876 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loaders': Unsatisfied dependency expressed through field 'operations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [com/demo/elastic/elasticdemo/config/ElasticConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.core.ElasticsearchOperations]: Factory method 'elasticsearchTemplate' threw exception; nested exception is java.lang.NoClassDefFoundError: org/elasticsearch/transport/Netty3Plugin
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]

Why DataSource cannot be autowired in spring boot application?

I know that spring boot will create a dataSource Bean automatically if related configurations are set in application.properties, like:
spring.datasource.url = jdbc:mysql://192.168.10.103:3306/hms?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=test#123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Application code:
package com.synline.mdataserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.apache.tomcat.jdbc.pool.DataSource;
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
AnnotationConfigApplicationContext context;
/*#Autowired
DataSource dataSource;*/
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
DataSource dataSource = (DataSource)context.getBean("dataSource");
System.out.println(dataSource);
while (true) {
Thread.sleep(5000);
}
}
}
If the #Autowired DataSource is commented out, the Bean information will be printed:
org.apache.tomcat.jdbc.pool.DataSource#1800a575{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....}
So I think Spring Boot really created the Bean.
But if #Autowried DataSource is used, exception occurs to complain No Such Bean
Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.tomcat.jdbc.pool.DataSource com.synline.mdataserver.Application.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.apache.tomcat.jdbc.pool.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Your variable should be declared as a standard JDBC DataSource (i.e. javax.sql.DataSource), not as a particular implementation of that interface.

Cannot use placeholder in static factory method creating a SpringLiquibase bean

Spring 3.1.0 with Liquibase 2.0.5 running on Glassfish 2.1.1 - From a long gone colleague I have inherited this applicationContext.xml which constructs a SpringLiquibase bean this way:
<bean id="liquibaseConfiguratore" factory-method="createLiquibaseBean" class="com.whatever.LiquibaseFactory">
<constructor-arg name="dataSource" ref="dataSourceConfiguratore"/>
<constructor-arg name="changeLog" value="classpath:liquibase/configuratore-db-changelog.xml"/>
<constructor-arg name="propFileName" value="/opt/whatever/ec_properties.properties"/>
</bean>
where LiquibaseFactory is a factory and the bean produced by the static method createLiquibaseBean has class
com.whatever.CustomLiquibase extends liquibase.integration.spring.SpringLiquibase
Now I need to parameterize the changeLog value, so that my bean declaration becomes:
<bean id="liquibaseConfiguratore" factory-method="createLiquibaseBean" class="com.whatever.LiquibaseFactory">
<constructor-arg name="dataSource" ref="dataSourceConfiguratore"/>
<constructor-arg name="changeLog" value="${tgo.liquibase.changelog.filename}"/>
<constructor-arg name="propFileName" value="/opt/whatever/ec_properties.properties"/>
</bean>
In order to set the correct value for the parameter, I browse the source of SpringLiquibase and I see that the String changeLog:
/**
* Sets a Spring Resource that is able to resolve to a file or classpath resource.
* An example might be <code>classpath:db-changelog.xml</code>.
*/
public void setChangeLog(String dataModel) { ... }
After reading this, I put the original string inside my properties file.
tgo.liquibase.changelog.filename=classpath:liquibase/configuratore-db-changelog.xml
and declare the props as:
<context:property-placeholder location="file:///opt/whatever/custom_properties.properties" />
But the bean fails during creation. Error message is:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibaseConfiguratore' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at
.....
Caused by: liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at liquibase.parser.ChangeLogParserFactory.getParser(ChangeLogParserFactory.java:61)
at liquibase.Liquibase.update(Liquibase.java:107)
at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:262)
Apparently the parser is found when there is a plain string in the XML. The moment I put a placeholder, the parser ain't there to be found. But it looks like the placeholder is resolved correctly, at least on screen...
I have tried some variations:
put file:/absolute/path/to/configuratore-db-changelog.xml in the property
put classpath*:liquibase/configuratore-db-changelog.xml in the property
put properties 'index=0,1,2' instead of 'name' inside tag constructor.arg
But the problem is still there.
How can I use a placeholder to specify the changeLog parameter?
HERE IS THE COMPLETE STACK TRACE:
[#|2014-06-25T09:19:54.860+0200|SEVERE|sun-appserver2.1|javax.enterprise.system.container.web|_ThreadID=12;_ThreadName=pool-1-thread-6;_RequestID=36e46602-c248-4e54-844e-6e5e11225bb8;|WebModule[/FastwebSme]PWC1275: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibaseConfiguratore' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4632)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5312)
at com.sun.enterprise.web.WebModule.start(WebModule.java:353)
at com.sun.enterprise.web.LifecycleStarter.doRun(LifecycleStarter.java:58)
at com.sun.appserv.management.util.misc.RunnableBase.runSync(RunnableBase.java:304)
at com.sun.appserv.management.util.misc.RunnableBase.run(RunnableBase.java:341)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: liquibase.exception.LiquibaseException: Cannot find parser that supports classpath:liquibase/configuratore-db-changelog.xml
at liquibase.parser.ChangeLogParserFactory.getParser(ChangeLogParserFactory.java:61)
at liquibase.Liquibase.update(Liquibase.java:107)
at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:262)
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 24 more
|#]
AND HERE IS LIQUIBASEFACTORY:
package com.whatever.util;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class LiquibaseFactory {
private static boolean enabled = !StringUtils.equals(
System.getProperty("liquibase.disable"), "true");
private static Logger log = Logger.getLogger(LiquibaseFactory.class);
public static CustomLiquibase createLiquibaseBean(DataSource dataSource,
String changeLog, String propFileName) {
log.info("dataSource is " + dataSource);
log.info("changeLog is " + changeLog);
log.info("propFileName is " + propFileName);
CustomLiquibase customLiquibase = null;
if (enabled) {
log.info("creating customLiquibase ENABLED");
customLiquibase = new CustomLiquibase(propFileName);
customLiquibase.setDataSource(dataSource);
customLiquibase.setChangeLog(changeLog);
} else {
log.warn("Liquibase has been disabled");
log.warn("\n\n" + StringUtils.repeat("*", 80));
log.warn(StringUtils.repeat("*", 80) + "\n\n");
}
return customLiquibase;
}
}
AND HERE IS CUSTOMLIQUIBASE:
package com.whatever.util;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import liquibase.integration.spring.SpringLiquibase;
import org.apache.log4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class CustomLiquibase extends SpringLiquibase {
private static final Logger LOGGER = Logger
.getLogger(CustomLiquibase.class);
public CustomLiquibase(String propertiesName) {
super();
LOGGER.info("propertiesName is " + propertiesName);
Resource resource = new FileSystemResource(new File(propertiesName));
try {
LOGGER.info("resource is " + resource);
Properties props = PropertiesLoaderUtils.loadProperties(resource);
Map<String, String> ps = new HashMap<String, String>();
for (Object key : props.keySet()) {
Object value = props.get(key);
if (value != null) {
ps.put(key.toString(), value.toString());
}
}
this.setChangeLogParameters(ps);
} catch (IOException ex) {
LOGGER.error("", ex);
}
}
}

Resources