lookup method - Injecting a prototype bean into a singleton bean issue - spring

I am developing code for the Injecting a prototype bean into a singleton bean code, so far I developed code like below and when I run the main method, I see the below error is coming.
Jan 04, 2017 2:59:41 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#6ed322: startup date [Wed Jan 04 14:59:41 IST 2017]; root of context hierarchy
Jan 04, 2017 2:59:41 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Constructor:: RequestProcessor instance created!
Constructor:: RequestProcessor instance created!
Request ID : 1212
Exception in thread "main" java.lang.AbstractMethodError: com.injection.testing.RequestProcessor.createValidator()Lcom/injection/testing/RequestValidator;
at com.injection.testing.RequestProcessor.handleRequest(RequestProcessor.java:12)
at com.injection.testing.MainDemo.main(MainDemo.java:13)
spring.xml
<!-- Lookup way -->
<bean id="requestProcessor" class="com.injection.testing.RequestProcessor" >
<lookup-method name="getValidator" bean="validator" />
</bean>
<bean id="validator" class="com.injection.testing.RequestValidator" scope="prototype" />
RequestProcessor.java
public abstract class RequestProcessor {
private RequestValidator validator;
public RequestProcessor(){
System.out.println("Constructor:: RequestProcessor instance created!");
}
public void handleRequest(String requestId){
System.out.println("Request ID : "+ requestId);
RequestValidator validator = createValidator(); //here Spring will create new instance of prototype bean
validator.validate(requestId);
}
public RequestValidator getValidator() {
return validator;
}
public void setValidator(RequestValidator validator) {
this.validator= validator;
}
protected abstract RequestValidator createValidator();
}
RequestValidator.java
public class RequestValidator {
private List<String> errorMessages = new ArrayList<String>();
public RequestValidator() {
System.out.println("Constructor:: RequestValidator instance created!");
}
// Validates the request and populates error messages
public void validate(String requestId){
System.out.println("RequestValidator :"+requestId);
}
public List<String> getErrorMessages() {
return errorMessages;
}
}
MainDemo.java
public class MainDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//RequestValidator requestValidator = (RequestValidator) context.getBean("validator");
RequestProcessor processor = (RequestProcessor) context.getBean("requestProcessor");
processor.handleRequest("1212");
System.out.println("------------------------");
processor.handleRequest("1213");
}
}
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

Update your spring.xml to shown below
<bean id="requestProcessor" class="com.injection.testing.RequestProcessor">
<lookup-method name="createValidator" bean="validator" />
</bean>
Basically you need to specify the name of the abstract method name in lookup-method xml attribute.
I got below output after the corrected configuration
Jan 04, 2017 4:11:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#13c675d: startup date [Wed Jan 04 16:11:20 IST 2017]; root of context hierarchy
Jan 04, 2017 4:11:20 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Constructor:: RequestProcessor instance created!
Request ID : 1212
Constructor:: RequestValidator instance created!
RequestValidator :1212
Request ID : 1213
Constructor:: RequestValidator instance created!
RequestValidator :1213

Related

#Autowired annotation in spring-Getting BeanCreationException and java.lang.NoSuchMethodError

I have written a small code to check #Autowired annotation in Spring, here is my piece of code.
package beans;
//import org.springframework.beans.factory.annotation.AutoWired;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.beans.factory.annotation.*;
public class Car {
#Autowired
#Qualifier(value="e1")
private Engine engine;
//no need to have setters or constructors here
public void printData()
{
System.out.println("Engine model year: " +engine.getModelyear());
}
}
package beans;
public class Engine {
private String modelyear;
//generate setter and getter
public void setModelyear(String modelyear) {
this.modelyear = modelyear;
}
public String getModelyear() {
return modelyear;
}
}
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Car;
//import beans.Test;
public class Client {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
Car c=(Car)ap.getBean("c");
c.printData();
}
}
<!--spring.xml-->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- activate autowire annotation -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="engine" class="beans.Engine">
<property name="modelyear" value="2015"/>
</bean>
<bean id="e1" class="beans.Engine">
<property name="modelyear" value="2016"/>
</bean>
<bean id="c" class="beans.Car">
</bean>
</beans>
When I am trying to run Client.java class ,I am getting following error:
Can someone suggest why I am facing this issue?
Mar 11, 2017 10:19:24 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#70d18a80: display name [org.springframework.context.support.ClassPathXmlApplicationContext#70d18a80]; startup date [Sat Mar 11 10:19:24 IST 2017]; root of context hierarchy
Mar 11, 2017 10:19:24 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resource/spring.xml]
Mar 11, 2017 10:19:25 AM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext#70d18a80]: org.springframework.beans.factory.support.DefaultListableBeanFactory#18d1cf9e
Mar 11, 2017 10:19:25 AM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Mar 11, 2017 10:19:25 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#18d1cf9e: defining beans [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor,engine,e1,c]; root of factory hierarchy
Mar 11, 2017 10:19:25 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#18d1cf9e: defining beans [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor,engine,e1,c]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'c': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private beans.Engine beans.Car.engine; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableListableBeanFactory.resolveDependency(Lorg/springframework/beans/factory/config/DependencyDescriptor;Ljava/lang/String;Ljava/util/Set;Lorg/springframework/beans/TypeConverter;)Ljava/lang/Object;
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private beans.Engine beans.Car.engine; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableListableBeanFactory.resolveDependency(Lorg/springframework/beans/factory/config/DependencyDescriptor;Ljava/lang/String;Ljava/util/Set;Lorg/springframework/beans/TypeConverter;)Ljava/lang/Object;
Caused by: java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableListableBeanFactory.resolveDependency(Lorg/springframework/beans/factory/config/DependencyDescriptor;Ljava/lang/String;Ljava/util/Set;Lorg/springframework/beans/TypeConverter;)Ljava/lang/Object;
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredElement.inject(AutowiredAnnotationBeanPostProcessor.java:361)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:61)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:414)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:249)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:155)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:246)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:291)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:122)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:66)
at test.Client.main(Client.java:13)
Set of jars which I am using are:
List of jars used and reference libraries while creating the project

Spring boot bean null exception

#SpringBootApplication
public class DataProcessorApplication {
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(DataProcessorApplication.class);
app.run();
}
PostProcessor class
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class BeanRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
private static final Logger LOG = LoggerFactory.getLogger(BeanRegistryPostProcessor.class);
#Autowired
private DataConfigurationService dataConfigurationService;
#Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory factory)
throws BeansException {
// we don't want to touch existing beans
}
#Override
public void postProcessBeanDefinitionRegistry(final BeanDefinitionRegistry registry){
dataConfigurationService.something(); // service bean is null here
}
}
My Service class
#Service
public class DataConfigurationService implements ApplicationListener<ApplicationReadyEvent> {
private static final Logger LOG = LoggerFactory.getLogger(DataConfigurationService.class);
#Override
public void onApplicationEvent(final ApplicationReadyEvent e) {
LOG.debug("Loading active DataConfiguration instance...");
}
}
Exception
java.lang.NullPointerException: null
at dataprocessor.configmodels.processor.BeanRegistryPostProcessor.postProcessBeanDefinitionRegistry(BeanRegistryPostProcessor.java:40)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:118)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:685)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:736)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at dataprocessor.DataProcessorApplication.main(DataProcessorApplication.java:47)
2017-01-07 12:42:47.802 WARN 8880 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7a138fc5: startup date [Sat Jan 07 12:42:46 CET 2017]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:416)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1004)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:963)
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:793)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
at dataprocessor.DataProcessorApplication.main(DataProcessorApplication.java:47)
2017-01-07 12:42:47.803 ERROR 8880 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7a138fc5: startup date [Sat Jan 07 12:42:46 CET 2017]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:403)
at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97)
at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:233)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:951)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:958)
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1035)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1011)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:963)
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:793)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
at dataprocessor.DataProcessorApplication.main(DataProcessorApplication.java:47)
POM
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
Spring initializes context in next sequence:
First, based on application configuration and automatically detected classes(#Component, #Service etc) bean definitions will be created and registered in BeanDefinitionRegistry.
After that Spring will auto-detect beans which implement BeanFactoryPostProcessor in their bean definitions and apply them before any other beans get created. Since your BeanRegistryPostProcessor is implementation of BeanFactoryPostProcessor it will be applied on this step.
After that Spring will auto-detect all beans which implement BeanPostProcessor interface and will apply them to any beans subsequently created. One of this beans is AutowiredAnnotationBeanPostProcessor which processes #Autoware annotation. That means your service will be injected on this step.
As you see you're trying to use DataConfigurationService bean before it will be injected into BeanRegistryPostProcessor. For solve this problem you can implement ApplicationContextAware interface in BeanRegistryPostProcessor and then get instance of service directly from application context:
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class BeanRegistryPostProcessor
implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware{
private ApplicationContext applicationContext;
...
#Override
public void postProcessBeanDefinitionRegistry(final BeanDefinitionRegistry registry){
DataConfigurationService service = applicationContext.getBean(DataConfigurationService.class);
service.something();
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
More details about so called Container Extension Points you can find in Spring documentation.

Spring context:component-scan not working with annotated beans

I'm trying to run a simple Spring + Hibernate tutorial => Maven Spring Hibernate annotation example
My beans definition file BeanLocations.xml is like this :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/Datasource.xml"/>
<import resource="../database/Hibernate.xml" />
<context:component-scan base-package="com.sample.springhibernate"/>
</beans>
My main method:
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath*:BeanLocations.xml");
StockBo stockBo = (StockBo)appContext.getBean("stockBo");
}
I have a defined service with an interface:
public interface StockBo {
public void save(Stock stock);
public void update(Stock stock);
public void delete(Stock stock);
public Stock findByStockCode(String stockCode);
}
And his implementation:
#Service("stockBo")
public class StockBoImpl implements StockBo {
#Autowired
StockDao stockDao;
public void setStockDao(StockDao stockDao){
this.stockDao = stockDao;
}
#Override
public void save(Stock stock) {
stockDao.save(stock);
}
........
There is any problem with this because spring throws a Exception when StockBo)appContext.getBean("stockBo") :
30-oct-2014 15:31:49 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#64dc11: display name [org.springframework.context.support.ClassPathXmlApplicationContext#64dc11]; startup date [Thu Oct 30 15:31:49 CET 2014]; root of context hierarchy
30-oct-2014 15:31:49 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext#64dc11]: org.springframework.beans.factory.support.DefaultListableBeanFactory#a3d4cf
30-oct-2014 15:31:49 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#a3d4cf: defining beans []; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'stockBo' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:387)
Spring not foud my annotated service StockBoo (with #Service("stockBo") )....
What is the problem? How can I ensure that Spring recognize my service with component scan?
FYI: StockBo is in com.sample.springhibernate.bo and StockBoImpl in com.sample.springhibernate.bo.impl
If you turn your log level to DEBUG, you'll more than likely find a line like
DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 0 bean definitions from location pattern [classpath*:BeanLocations.xml]
That is, your ClassPathXmlApplicationContext did not find any resources that match classpath*:BeanLocations.xml and therefore didn't load any context.
You'll need to provide a resource location String value that properly identifies and locates the context configuration file.

Issues with Oracle JDBC with Hibernate... Sometimes

I'm having a bit of a unique issue.
I'm able to successfully connect and manage entities when running JUnit tests, but once I start my actual application, I get "Specified JDBC Driver oracle.jdbc.OracleDriver class not found."
What confuses me is that it is there. It works when running my JUnit Tests.
Any insights are appreciated!
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="db">
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#host:port/db</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">db</property>
<property name="show_sql">true</property>
<mapping resource="org/entity/RunResultEntity.hbm.xml"/>
<mapping resource="org/entity/TransactionResultEntity.hbm.xml"/>
<mapping resource="org/entity/FailureResultEntity.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package org.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.*;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()
).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Exception thrown here!
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
pom.xml (dependency added to local repository)
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3.0</version>
<scope>provided</scope>
</dependency>
log
Oct 09, 2014 3:02:58 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Oct 09, 2014 3:02:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/RunResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/TransactionResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/FailureResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: db
Oct 09, 2014 3:02:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Initial SessionFactory creation failed.org.hibernate.HibernateException: Specified JDBC Driver oracle.jdbc.OracleDriver class not found
Exception in thread "main" java.lang.ExceptionInInitializerError
I found my problem. Lower in my pom.xml I had this little snippet
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
The classifier was only giving access to my test suite. Removing the classifier fixed the issue.
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
</dependency>

Getting Bean Creation error while refering prototype bean inside singleton bean

Getting Bean Creation error while refering prototype bean inside singleton bean please have a look in my following code snapshot
Sep 1, 2014 12:36:03 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#100ab23: startup date [Mon Sep 01 00:36:03 IST 2014]; root of context hierarchy
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5dcec6: defining beans [triangle,pointA,pointB,pointC,circle]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pointA' defined in class path resource [spring.xml]: 1 constructor arguments specified but no matching constructor found in bean 'pointA' (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:175)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:993)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:897)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1087)
at org.koushik.javabrrians.Triangle.getPointA(Triangle.java:18)
at org.koushik.javabrrians.Triangle.draw(Triangle.java:46)
at org.koushik.javabrrians.DrawingApp.main(DrawingApp.java:26)
My Triangle class is like this
package org.koushik.javabrrians;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Triangle implements ApplicationContextAware {
private Point pointA;
private Point pointB;
private Point pointC;
ApplicationContext context = null;
public Point getPointA() {
//return pointA;
return (Point) context.getBean("pointA" , "Point.class");
}
public void setPointA(Point pointA) {
this.pointA = pointA;
}
public Point getPointB() {
//return pointB;
return (Point) context.getBean("pointB" , "Point.class");
}
public void setPointB(Point pointB) {
this.pointB = pointB;
}
public Point getPointC() {
//return pointC;
return (Point) context.getBean("pointC" , "Point.class");
}
public void setPointC(Point pointC) {
this.pointC = pointC;
// context.getBean("pointC");
}
public void draw() {
System.out.println("PoinA X = " + getPointA().getX() + " Y = " + getPointA().getY());
System.out.println("PoinB X = " + getPointB().getX() + " Y = " + getPointB().getY());
System.out.println("PoinC X = " + getPointC().getX() + " Y = " + getPointC().getY());
}
#Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.context = arg0;
}
}
My Circle Class is like this
package org.koushik.javabrrians;
public class Circle {
private Point centre;
public Point getCentre() {
return centre;
}
public void setCentre(Point centre) {
this.centre = centre;
}
public void draw() {
System.out.println("PoinA Centre = " + getCentre().getX() + " Y = " + getCentre().getY());
}
}
My Point Class is like this
package org.koushik.javabrrians;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
My Spring Configuration file is like this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="triangle" class="org.koushik.javabrrians.Triangle" autowire = "byName" scope = "singleton">
</bean>
<bean id="pointA" class="org.koushik.javabrrians.Point" scope = "prototype">
<property name="x" value="0" />
<property name="y" value="0" />
</bean>
<bean id="pointB" class="org.koushik.javabrrians.Point" scope = "prototype">
<property name="x" value="-20" />
<property name="y" value="0" />
</bean>
<bean id="pointC" class="org.koushik.javabrrians.Point" scope = "prototype">
<property name="x" value="0" />
<property name="y" value="20" />
</bean>
<bean id="circle" class="org.koushik.javabrrians.Circle" scope = "prototype">
<property name="centre" ref="pointA" />
</bean>
</beans>
I am Getting following Error after execution
Sep 1, 2014 12:36:03 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#100ab23: startup date [Mon Sep 01 00:36:03 IST 2014]; root of context hierarchy
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5dcec6: defining beans [triangle,pointA,pointB,pointC,circle]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pointA' defined in class path resource [spring.xml]: 1 constructor arguments specified but no matching constructor found in bean 'pointA' (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:175)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:993)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:897)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1087)
at org.koushik.javabrrians.Triangle.getPointA(Triangle.java:18)
at org.koushik.javabrrians.Triangle.draw(Triangle.java:46)
at org.koushik.javabrrians.DrawingApp.main(DrawingApp.java:26)
The immediate cause of the error is the quotes around "Point.class". Remove them (and you can also then remove the cast):
public Point getPointA() {
//return pointA;
return context.getBean("pointA" , Point.class);
}
(and similarly for the other methods). Your version is treated as a call to the varargs method getBean(String name, Object... args) where args are constructor arguments, and your Point class does not have a constructor taking a String parameter. Without the quotes it's a call to the non-varargs method getBean(String name, Class<T> type) where the second argument is the type of the bean you're retrieving.

Resources