AOP-afterReturning throws NullPointerException - java

Spring configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" >
<!-- Enable AspectJ style of Spring AOP -->
<aop:aspectj-autoproxy />
<bean id="studService" class="springAOP.Student">
<property name="age" value="20"></property>
<property name="name" value="Sangeetha"></property>
</bean>
<bean id="logging" class="springAOP.Logging"/>
<aop:config>
<aop:aspect id="log" ref="logging" >
<aop:pointcut id="student" expression="execution(* springAOP.Student.*(..))" />
<!-- before advice definition -->
<aop:before pointcut-ref="student" method="beforeAdvice"/>
<!-- after advice definition -->
<aop:after pointcut-ref="student" method="afterAdvice"/>
<!-- after-returning advice -->
<aop:after-returning pointcut-ref="student" method="afterReturningAdvice" returning="retVal"/>
<!-- after throwing advice -->
<aop:after-throwing pointcut-ref="student" method="afterThrowingAdvice" throwing="ex"/>
<!-- around advice -->
<aop:around pointcut-ref="student" method="aroundAdvice"/>
</aop:aspect>
</aop:config>
Application class
package spring;
import springAOP.Student;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringApp {
private AbstractApplicationContext context;
HelloWorld obj;
Student student;
public SpringApp()
{
context = new ClassPathXmlApplicationContext("spring-beans.xml");
}
public void initializeBeans(){
obj = (HelloWorld)context.getBean("sayHello");
student = (Student)context.getBean("studService");
}
public static void main(String args[]){
SpringApp app = new SpringApp();
app.initializeBeans();
System.out.println(" getting name and age");
Student stud = (Student)app.context.getBean("studService");
stud.getName();
stud.getAge();
}
EntityClass
package springAOP;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
System.out.println("Setting Age : " + age);
}
public Integer getAge() {
System.out.println("Age : " + age);
return age;
}
public void setName(String name) {
this.name = name;
System.out.println("Setting Name : " + name);
}
public String getName() {
System.out.println("Name : " + name);
return name;
}
public void printThrowException() {
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Output:
Jul 17, 2015 9:51:50 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#ad9418: startup date [Fri Jul 17 21:51:50 IST 2015]; root of context hierarchy
Jul 17, 2015 9:51:51 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-beans.xml]
Jul 17, 2015 9:51:52 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#e2abd: defining beans [org.springframework.aop.config.internalAutoProxyCreator,studService,logging,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,org.springframework.aop.aspectj.AspectJPointcutAdvisor#4,student,employee,employeeService,dataSource,sayHello,spellCheck]; root of factory hierarchy
Setting Age : 20
Setting Name : Sangeetha
Jul 17, 2015 9:51:53 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: oracle.jdbc.driver.OracleDriver
Setting Message is : you are in spring Hello World
i m in init
i 2 j 3
Going to setup student profile.
After smooth execution
Returning:null
Student profile has been setup.
Going to setup student profile.
After smooth execution
Returning:null ==> returning NULL
Student profile has been setup.
Logging.java:
package springAOP;
public class Logging {
/**
* * This is the method which I would like to execute * before a selected
* method execution.
*/
public void beforeAdvice() {
System.out.println("Going to setup student profile.");
}
/**
* * This is the method which I would like to execute * after a selected
* method execution.
*/
public void afterAdvice() {
System.out.println("Student profile has been setup.");
}
/**
* * This is the method which I would like to execute * when any method
* returns.
*/
public void afterReturningAdvice(String retVal) {
System.out.println("Returning:" + retVal);
}
/**
* * This is the method which I would like to execute * if there is an
* exception raised.
*/
public void afterThrowingAdvice(IllegalArgumentException ex) {
System.out.println("There has been an exception: " + ex.toString());
}
public void aroundAdvice(){
System.out.println("After smooth execution " );
}
}
Issue:
When the getName and getAge methods are accessed, afterReturning is not getting retValue, value is passed as NULL. Kindly help me to understand why value is passed as NULL

You can use the ProceedingJoinPoint of aspectJ.
public void afterReturningAdvice(ProceedingJoinPoint joinpoint) {
Object[] args = joinpoint.getArgs()
Object retVal = null;
if(args.length > 0) {
retVal = args[0];
}
System.out.println("Returning:" + retVal);
}

Related

I am trying to connect to a database that I created with java using hibernate. I am getting this error and I am not sure why

I am trying to connect to a database that I created with java in eclipse using hibernate. It is supposed to connect to the payroll database and insert records into the student table but I am getting this error! I inserted the jdbc connect and the other required jar files. I am not sure why it's not working. Please help.
Error:
Jul 14, 2022 2:34:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.3.Final
Jul 14, 2022 2:34:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/payroll]
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 3 (min=1)
Jul 14, 2022 2:34:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Jul 14, 2022 2:34:11 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#304b9f1a] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate:
select
student0_.id as id1_0_,
student0_.email as email2_0_,
student0_.first_name as first_na3_0_,
student0_.last_name as last_nam4_0_
from
student student0_
Hibernate:
select
student0_.id as id1_0_0_,
student0_.email as email2_0_0_,
student0_.first_name as first_na3_0_0_,
student0_.last_name as last_nam4_0_0_
from
student student0_
where
student0_.id=?
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl#5eb97ced is closed
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:137)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:276)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:121)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304)
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142)
at models.Student.get(Student.java:131)
at Driver.main(Driver.java:24)
Driver Class(driver.java)
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import models.Student;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu =new Student();//1,"Simone","Charles","#Home");
//stu.create();
List<Student> students=stu.readAll();
for(Student s: students) {
System.out.println(s.getFirstName());
}
Student s1=stu.get(4);
System.out.println(s1.getFirstName());
//sstu.delete(2);
//getCurrentSessionFromConfig();
}
public static Session getCurrentSessionFromConfig() {
// SessionFactory in Hibernate 5 example
Configuration config = new Configuration();
config.configure();
// local SessionFactory bean created
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
return session;
}
public static Session getCurrentSessionX() {
// Hibernate 5.4 SessionFactory example without XML
Map<String, String> settings = new HashMap<>();
settings.put("connection.driver_class", "com.mysql.jdbc.Driver");
settings.put("dialect", "org.hibernate.dialect.MySQL8Dialect");
settings.put("hibernate.connection.url",
"jdbc:mysql://localhost/hibernate_examples");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "");
settings.put("hibernate.current_session_context_class", "thread");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.format_sql", "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(settings).build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
// metadataSources.addAnnotatedClass(Player.class);
Metadata metadata = metadataSources.buildMetadata();
// here we build the SessionFactory (Hibernate 5.4)
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
Session session = sessionFactory.getCurrentSession();
return session;
}
}
Hibernate xml file
<?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">
<!-- Version 8 MySQL hiberante-cfg.xml example for Hibernate 5 -->
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- property name="connection.driver_class">com.mysql.jdbc.Driver</property -->
<property name="connection.url">jdbc:mysql://localhost/payroll</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">3</property>
<!--property name="dialect">org.hibernate.dialect.MySQLDialect</property-->
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- mapping class="com.mcnz.jpa.examples.Player" / -->
<mapping class="models.Student" />
</session-factory>
</hibernate-configuration>
SessionBuilder File
package factories;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import models.Student;
public class SessionFactoryBuilder {
private static SessionFactory sessionFactory = null;
public static SessionFactory getSessionFactory () {
if(sessionFactory==null) {
try {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
// session =sessionFactory.openSession();
/* sessionFactory =new
Configuration().configure("hibernate.cfg.xml").addAnnotatedClass
(Student.class).buildSessionFactory();
*/
}catch(RuntimeException e) {System.out.println(e.toString());}
}
return sessionFactory;
}
public static void closeSessionFactory () {
if(sessionFactory!=null) {
sessionFactory.close();
}
}
}
Student Class
package models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import factories.SessionFactoryBuilder;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
int id;
#Column(name="first_name")
String firstName;
#Column(name="last_name")
String lastName;
#Column(name="email")
String email;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String firstName, String lastName, String email) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void create() {
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//stu.setFirstName(firstName);
//stu.setLastName(lastName);
session.save(this);
transaction.commit();
session.close();
}
public List<Student> readAll(){
List<Student> studentList=new ArrayList<>();
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
studentList=(List<Student>) session.createQuery("From Student").getResultList();
transaction.commit();
session.close();
return studentList;
}
public void delete(int id) {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//session.delete(stu);
// Delete a persistent object
Student student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println("student deleted");
}
// Delete a transient object
/* Student student2 = new Student();
student2.setId(2);
session.delete(student2);
System.out.println("Student 2 is deleted");
*/
transaction.commit();
session.close();
}
public void update() {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
session.update(this);
transaction.commit();
session.close();
}
public Student get(int id) {
Student stu=null;
Transaction transaction=null;
try(Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession()){
transaction= session.beginTransaction();
stu=(Student) session.get(Student.class, id);
session.delete(stu);
transaction.commit();
}catch(Exception e) {
if(transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
return stu;
}
}

Spring can't find bean and throws NoSuchBeanDefinitionException

I have a problem with a realization of Spring in Action example of a programme.
Test class:
#Test
public void testBasicUsage() throws PerformanceException {
ApplicationContext context = new ClassPathXmlApplicationContext("/**/java/springidol/spring-idol.xml");
Performer performer = (Performer) context.getBean("juggler");
performer.perform();
}
Juggler class that should be configured by Spring
public class Juggler implements Performer {
private int beanBags = 3;
public Juggler() {
}
public Juggler(int beanBags) {
this.beanBags = beanBags;
}
#Override
public void perform() throws PerformanceException {
System.out.println("JUGGLING " + beanBags + " BEANBAGS");
}
}
And xml configuration file for this bean:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="juggler"
class="springidol.Juggler">
<constructor-arg value="15"/>
</bean>
</beans>
this code throw NoSuchBeanDefinitionException:
Aug 30, 2018 1:20:43 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1c53fd30: startup date [Thu Aug 30 13:20:43 EEST 2018]; root of context hierarchy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'juggler' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:686)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
at springidol.TestMain.testBasicUsage(TestMain.java:12)
I think the class-path you provided in ClassPathXmlApplicationContextshould be where the XML configuration in present. The files on classpaths are automatically scanned, we just need to provide folder paths.
Try below in Test class with changes:
ApplicationContext context = new ClassPathXmlApplicationContext("java/springidol/spring-idol.xml");
Reference: Spring Source

Hibernate 5 Transaction not started by Spring 4

Based on this tutorial, I was trying to manage Hibernate 5 transactions with Spring 4. It seems that the transaction has not been started when session.get() method is reached. How does Spring knows when to start and end a transaction? Shouldn't the #Transactional annotation do precisely this?
Entity
package coproject.cpweb.utils.db.entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import coproject.cpweb.utils.db.entities.Project;
import coproject.cpweb.utils.db.entities.User;
#Entity
#Table( name = "users" )
public class Cbtion {
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy = "increment")
private Integer id;
#ManyToOne
private Project project;
#ManyToOne
private User creator;
private Date creationDate;
private String title;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DAO
package coproject.cpweb.utils.db.daos;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import coproject.cpweb.utils.db.entities.User;
#Service
public class CbtionDAO {
#Autowired
SessionFactory sessionFactory;
public void saveUser(User user) {
Session session = sessionFactory.getCurrentSession();
User user_indb = session.get(User.class,user.getId());
if(user_indb == null) {
session.save(user);
}
else {
user = user_indb;
}
}
public User getUser(Integer id) {
Session session = sessionFactory.getCurrentSession();
User user = session.get(User.class,id);
return user;
}
}
Service
package coproject.cpweb.utils.db.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import coproject.cpweb.utils.DbServicesIf;
import coproject.cpweb.utils.db.daos.CbtionDAO;
import coproject.cpweb.utils.db.entities.User;
#Service
public class DbServicesImp implements DbServicesIf{
#Autowired
private CbtionDAO cbtionDAO;
#Transactional
public void saveUser(User user) {
cbtionDAO.saveUser(user);
}
#Transactional
public User getUser(Integer id) {
return cbtionDAO.getUser(id);
}
}
context beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" >
<tx:annotation-driven />
<context:component-scan base-package="coproject.cpweb.utils.db.entities" />
<context:component-scan base-package="coproject.cpweb.utils.db.daos" />
<context:component-scan base-package="coproject.cpweb.utils.db.services" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="jaof" />
<property name="password" value="iris" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<list>
<value>coproject.cpweb.utils.db.entities</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
Main
package coproject.cploc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import coproject.cpweb.utils.db.entities.User;
import coproject.cpweb.utils.db.services.DbServicesImp;
public class FillRandomDb {
public static void main(String[] args) throws Exception {
#SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// TEST String[] bean_names = context.getBeanDefinitionNames();
DbServicesImp dbServices = (DbServicesImp) context.getBean("dbServicesImp");
User user = new User();
user.setUsername("johndoe");
user.setFirstname("John");
user.setLastname("Doe");
dbServices.saveUser(user);
User user_ret = dbServices.getUser(user.getId());
System.out.println(user_ret.getFirstname());
}
}
Stack
nov 29, 2015 1:45:37 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#506e6d5e: startup date [Sun Nov 29 13:45:37 CE
T 2015]; root of context hierarchy
nov 29, 2015 1:45:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
nov 29, 2015 1:45:38 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
nov 29, 2015 1:45:38 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
nov 29, 2015 1:45:38 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
nov 29, 2015 1:45:38 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
nov 29, 2015 1:45:38 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
nov 29, 2015 1:45:39 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
nov 29, 2015 1:45:45 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
nov 29, 2015 1:45:46 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
nov 29, 2015 1:45:46 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#5e1d03d7] of Hibernate SessionFactory for HibernateTransactionMana
ger
Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:33
4)
at com.sun.proxy.$Proxy23.get(Unknown Source)
at coproject.cpweb.utils.db.daos.CbtionDAO.saveUser(CbtionDAO.java:19)
at coproject.cpweb.utils.db.services.DbServicesImp.saveUser(DbServicesImp.java:20)
at coproject.cpweb.utils.db.services.DbServicesImp$$FastClassBySpringCGLIB$$cd649fcb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281
)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at coproject.cpweb.utils.db.services.DbServicesImp$$EnhancerBySpringCGLIB$$75288f15.saveUser(<generated>)
at coproject.cploc.FillRandomDb.main(FillRandomDb.java:24)
Try to change this line in your file context beans.xml:
<prop key="hibernate.current_session_context_class">thread</prop>
With this line:
<prop key="current_session_context_class">thread</prop >
And for annotation support, in your spring config bean, add this:
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true" />
DAO class should be annotated as #Repository.

Spring won't instantiate and I keep getting this infinite loop

I'm trying to find out what have I done wrong. It would be great if anyone could help me. I keep getting this in an infinite loop:
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#799f7e29: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#548a9f61: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
UsersDAOImp :
public class UsersDAOImp extends GenericEntityDAO implements UsersDAO {
private SessionFactory sessionFactory = (SessionFactory) BeanManager.getBean("sessionFactory");
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Users> selectAll() {
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Users.class);
List<Users> users = (List<Users>) criteria.list();
session.getTransaction().commit();
return users;
}
}
UsersService
public class UsersService {
UsersDAOImp usersDAO = new UsersDAOImp();
public void setUsersDAO(UsersDAOImp usersDAO) {
this.usersDAO = usersDAO;
}
public UsersDAOImp getUsersDAO() {
return usersDAO;
}
public List<Users> getAllUsers() {
return getUsersDAO().selectAll();
}
}
Bean manager used to get context
public class BeanManager {
/* BeanManager is used to parse Beans.xml file */
private static ApplicationContext context;
private BeanManager() {
}
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
BeanManager.context = context;
}
public static Object getBean(String beanId) {
if (context == null) {
context = new ClassPathXmlApplicationContext("Beans.xml");
}
Object result = context.getBean(beanId);
return result;
}
}
This is my Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="usersDAO" class="com.survey.persistance.DAO.UsersDAOImp" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/app" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>

Error while creating bean: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError

I am facing the following error when I try to create bean using Application Context for the circle class! Circle class implements the Shape interface which contains a method draw().
Configuration:
I am learning spring and have setup a Java Project in eclipse with all the required jars (Spring and Apache commons logging). I have the spring.xml in my classpath in the src folder. Have also tried downloading the latest jars (Spring 4.0.4 release, previously worked with 4.0.0) but now is not working. Cannot think of any solution to fix this.
Error:
May 11, 2014 6:20:50 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#90832e: startup date [Sun May 11 18:20:50 EDT 2014]; root of context hierarchy
May 11, 2014 6:20:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor': Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:88)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.springApplication.DrawingApplication.main(DrawingApplication.java:16)
Caused by: java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1071)
... 13 more
Caused by: java.lang.NullPointerException
at org.springframework.beans.PropertyEditorRegistrySupport.<clinit>(PropertyEditorRegistrySupport.java:92)
... 14 more
DrawingApplication.java
package com.springApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApplication {
public static void main(String[] args) {
//The beanFactory reads from an XML file
//BeanFactory context = new XmlBeanFactory(new FileSystemResource("spring.xml"));
//Application Context provides -- Event notification and more than Bean Factory
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//Here we pass the id of the bean from the XML given in the above line
Shape shape = (Shape)context.getBean("circle");
//Calling the draw method through object local object created using Spring
shape.draw();
}
}
Circle.java
package com.springApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Circle implements Shape{
private Point center;
public Point getCenter() {
return center;
}
#Autowired
#Qualifier("circleRelated")
public void setCenter(Point center) {
this.center = center;
}
#Override
public void draw() {
System.out.println("Drawing a Circle");
System.out.println("Center Point is: (" + center.getX() + ", " + center.getY() + ")");
}
}
Point.java
package com.springApplication;
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;
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="pointA" class="com.springApplication.Point">
<qualifier value="circleRelated" />
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>
<bean id="PointB" class="com.springApplication.Point">
<property name="x" value="0"/>
<property name="y" value="20"/>
</bean>
<bean id="PointC" class="com.springApplication.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>
<bean id="circle" class="com.springApplication.Circle">
</bean>
<!-- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> -->
<context:annotation-config/>
</beans>
Please let me know if anything else is needed. Someone please help !
Sorry about the wrong placing!!
#Andrei Stefan
List of Jars ---------
commons-logging-1.1.3
spring-aop-4.0.4.RELEASE
spring-aop-4.0.4.RELEASE-javadoc
spring-aop-4.0.4.RELEASE-sources
spring-aspects-4.0.4.RELEASE
spring-aspects-4.0.4.RELEASE-javadoc
spring-aspects-4.0.4.RELEASE-sources
spring-beans-4.0.4.RELEASE
spring-beans-4.0.4.RELEASE-javadoc
spring-beans-4.0.4.RELEASE-sources
spring-build-src-4.0.4.RELEASE
spring-context-4.0.4.RELEASE
spring-context-4.0.4.RELEASE-javadoc
spring-context-4.0.4.RELEASE-sources
spring-context-support-4.0.4.RELEASE
spring-context-support-4.0.4.RELEASE-javadoc
spring-context-support-4.0.4.RELEASE-sources
spring-core-4.0.4.RELEASE
spring-core-4.0.4.RELEASE-javadoc
spring-core-4.0.4.RELEASE-sources
spring-expression-4.0.4.RELEASE
spring-expression-4.0.4.RELEASE-javadoc
spring-expression-4.0.4.RELEASE-sources
spring-framework-bom-4.0.4.RELEASE
spring-framework-bom-4.0.4.RELEASE-javadoc
spring-framework-bom-4.0.4.RELEASE-sources
spring-instrument-4.0.4.RELEASE
spring-instrument-4.0.4.RELEASE-javadoc
spring-instrument-4.0.4.RELEASE-sources
spring-instrument-tomcat-4.0.4.RELEASE
spring-instrument-tomcat-4.0.4.RELEASE-javadoc
spring-instrument-tomcat-4.0.4.RELEASE-sources
spring-jdbc-4.0.4.RELEASE
spring-jdbc-4.0.4.RELEASE-javadoc
spring-jdbc-4.0.4.RELEASE-sources
spring-jms-4.0.4.RELEASE
spring-jms-4.0.4.RELEASE-javadoc
spring-jms-4.0.4.RELEASE-sources
spring-messaging-4.0.4.RELEASE
spring-messaging-4.0.4.RELEASE-javadoc
spring-messaging-4.0.4.RELEASE-sources
spring-orm-4.0.4.RELEASE
spring-orm-4.0.4.RELEASE-javadoc
spring-orm-4.0.4.RELEASE-sources
spring-oxm-4.0.4.RELEASE
spring-oxm-4.0.4.RELEASE-javadoc
spring-oxm-4.0.4.RELEASE-sources
spring-test-4.0.4.RELEASE
spring-test-4.0.4.RELEASE-javadoc
spring-test-4.0.4.RELEASE-sources
spring-tx-4.0.4.RELEASE
spring-tx-4.0.4.RELEASE-javadoc
spring-tx-4.0.4.RELEASE-sources
spring-web-4.0.4.RELEASE
spring-web-4.0.4.RELEASE-javadoc
spring-web-4.0.4.RELEASE-sources
spring-webmvc-4.0.4.RELEASE
spring-webmvc-4.0.4.RELEASE-javadoc
spring-webmvc-4.0.4.RELEASE-sources
spring-webmvc-portlet-4.0.4.RELEASE
spring-webmvc-portlet-4.0.4.RELEASE-javadoc
spring-webmvc-portlet-4.0.4.RELEASE-sources
spring-websocket-4.0.4.RELEASE
spring-websocket-4.0.4.RELEASE-javadoc
spring-websocket-4.0.4.RELEASE-sources
All of these plus other default system libraries are referenced.
The problem occurs because
PropertyEditorRegistrySupport.class.getClassLoader()
is null. According to JavaDoc, this happens if the class PropertyEditorRegistrySupport has been loaded by the bootstrap class loader instead of the system class loader:
Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.
Perhaps your Spring libraries are on the endorsed class path?

Categories

Resources