Spring context:component-scan not working with annotated beans - spring

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.

Related

Using #Component for bean throws error. NoSuchBeanDefinitionException

I'm trying to create a simple spring app, but when i use #Component annotation for a bean instead of defining it in spring.xml file, I'm getting this error.
Aug 09, 2017 11:06:03 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#7e32c033: startup date [Wed Aug 09 11:06:03 IST 2017]; root of context hierarchy
Aug 09, 2017 11:06:03 AM 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.NoSuchBeanDefinitionException: No bean named 'oval' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
at org.sumit.javabrains.DrawingApp.main(DrawingApp.java:24)
My Classes are al follows:
1. DrawingApp.java (main class)
public package org.sumit.javabrains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) throws InterruptedException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Oval oval = (Oval) context.getBean("oval");
oval.draw();
}
}
2. 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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.sumit.javabrains" />
<context:annotation-config />
<bean id="focus" class="org.sumit.javabrains.Point" scope="singleton">
<property name="x" value="-7" />
<property name="y" value="8" />
</bean>
</beans>
3 Point.java
package org.sumit.javabrains;
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;
}
}
4 Oval.java
package org.sumit.javabrains;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
#Component
public class Oval {
private Point focus;
public Point getFocus() {
return focus;
}
#Resource
public void setFocus(Point focus) {
this.focus = focus;
}
public void draw() {
System.out.println("Point focus is: ("+focus.getX()+", "+focus.getY()+")");
}
}
could someone be able to help what caused this issue. I'm using spring 4.3.10 RELEASE
That's because your component scan is scanning the wrong packages
<context:component-scan base-package="com.sumit.javabrains" /> - Wrong
It should be scanning as follows:
<context:component-scan base-package="org.sumit.javabrains" /> - Correct
you must define all your bean in spring.xml. in this scenario you missed the Oval class in you spring configuration files. define the Oval class as a bean in your spring.xml file.
or
edit your component-scan tag and put the correct package.
Two thing went wrong here.
1. You've mentioned wrong base package in your xml file
com.sumit.javabrains must be replaced with org.sumit.javabrains
Replace #Resource with #Resource #Qualifier("focus").By default beans marked with ‘#Component’ will have the same name as the class
Try using #ComponentScan instead of #Component on top of the Oval class.
I wasn't using a spring.xml file (just the default spring boot configuration instead), my #SpringBootApplication annotated class was one package level deeper than my #Component class, which made that the #Component class wasn't picked up.
E.g.:
com.company.base/ComponentAnnotatedClass.java
com.company.base.application/MySpringBootApplication.java

Issue while running spring ; No error logs

I am a new bee to spring and am writing my first spring program.I have the following files.
package com.springstarter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUser
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
SpringStarter starter = ( SpringStarter ) context.getBean( "springstarter" );
starter.getMessage();
}
}
I have a bean called SpringStarter
package com.springstarter;
public class SpringStarter
{
private String message;
public String getMessage()
{
return message;
}
public void setMessage( String message )
{
this.message = message;
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="springstarter" class="com.springstarter.SpringStarter">
<property name="message" value="Hello World!"/>
</bean>
</beans>
The following is the package structure:
I have run the program in eclipse Mars, using Spring 4.2.4.
I didn't find any compilation issues, but the program is just showing the following logs.
Jan 14, 2016 10:36:08 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#73a83205: startup date [Thu Jan 14 10:36:08 IST 2016]; root of context hierarchy
Jan 14, 2016 10:36:08 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
The expected output though, is Hello World!
Kindly let me know if i'm making any obvious mistakes.
Nothing wrong, but to print the output on console, so you should use it like:
System.out.println(starter.getMessage());

How to solve "FactoryBean threw exception on object creation;"

I am experimenting on "beforeAdvice" over "JointPoints" in spring aop. it's pretty simple i am calling target method. before executing target class method, before() method should execute.
ClientApp:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.nt.services.LoanApprover;
public class ClientApp {
public static void main(String[] args) {
//activate ioc container
ApplicationContext context = new FileSystemXmlApplicationContext("src/com/nt/cfgs/applicationContext.xml");
//get bean
LoanApprover approver = context.getBean("pfb",LoanApprover.class);
//call b.method
approver.approver();
}
}
applicationContext.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="auditAdvice" class="com.nt.aspect.MyBeforeAdvice" />
<bean id="target" class="com.nt.services.LoanApprover" />
<bean id="pfb" class="
org.springframework.aop.framework.ProxyFactoryBean ">
<property name="target" ref="target" />
<property name="interceptorNames">
<list>
<value>
auditAdvice
</value>
</list>
</property>
</bean>
</beans>
MyBeforeAdvice.java
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeAdvice implements MethodBeforeAdvice{
#Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("I am in MyBeforeAdvice class");
}
}
LoanApprover.java
public class LoanApprover {
public void approver(){
System.out.println("I am in LoanApprover method");
}
}
when i run this application i am getting this exception.
Aug 13, 2015 12:16:04 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#7c6cd67b: startup date [Thu Aug 13 12:16:04 IST 2015]; root of context hierarchy
Aug 13, 2015 12:16:04 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [G:\java\Frameworks\SpringAOP\AOPProj3(Before Advice)\src\com\nt\cfgs\applicationContext.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pfb': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '
auditAdvice
' is defined
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObject FromFactoryBean(FactoryBeanRegistrySupport.java:175)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFr omFactoryBean(FactoryBeanRegistrySupport.java:103)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanIn stance(AbstractBeanFactory.java:1517)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(Abstract BeanFactory.java:251)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBe anFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractA pplicationContext.java:962)
at test.ClientApp.main(ClientApp.java:13)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '
auditAdvice
' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefi nition(DefaultListableBeanFactory.java:694)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBean Definition(AbstractBeanFactory.java:1168)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(Abstract BeanFactory.java:281)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBe anFactory.java:194)
at org.springframework.aop.framework.ProxyFactoryBean.initializeAdvisorChain(ProxyF actoryBean.java:460)
at org.springframework.aop.framework.ProxyFactoryBean.getObject(ProxyFactoryBean.ja va:244)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObject FromFactoryBean(FactoryBeanRegistrySupport.java:168)
... 6 more
please anyone tell me why i am getting this exception?
Simply change
<value>
auditAdvice
</value>
to
<value>auditAdvice</value>
It seems like spring is using whitespaces and newline symbols as ID here.
Further information on that topic is available here.
Hope that helps.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I created an application with spring + hibernate, but I always get this error. This is my first application with hibernate, I read some guides but I can not solve this problem. Where am I doing wrong?
This is the code of my application
ott 05, 2014 4:03:06 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
Informazioni: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1eab16b: startup date [Sun Oct 05 16:03:06 CEST 2014]; root of context hierarchy
ott 05, 2014 4:03:06 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
Informazioni: Loading XML bean definitions from class path resource [springConfig.xml]
ott 05, 2014 4:03:08 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
ott 05, 2014 4:03:08 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
ott 05, 2014 4:03:08 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
ott 05, 2014 4:03:08 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
ott 05, 2014 4:03:09 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
ott 05, 2014 4:03:09 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
ott 05, 2014 4:03:09 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at coreservlets.StudentDAOImpl.create(StudentDAOImpl.java:19)
at coreservlets.MainApp.main(MainApp.java:14)
student.java
package coreservlets;
public class Student {
private Integer id;
private String name;
private Integer age;
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
public String getName(){return name;}//getName
public void setName(String name){this.name=name;}//setName
public Integer getAge(){return age;}//getAge
public void setAge(Integer age){this.age=age;}//setAge
}//Student
studentDAO.java
package coreservlets;
import org.hibernate.SessionFactory;
public interface StudentDAO {
public void setSessionFactory(SessionFactory sessionFactory);
public void create(String name,Integer age);
}//StudentDAO
StudentDAOImpl.java
package coreservlets;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class StudentDAOImpl implements StudentDAO {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}//setSessionFactory
public void create(String name,Integer age){
Session session=sessionFactory.getCurrentSession();
Student student=new Student();
student.setName(name);
student.setAge(age);
session.save(student);
}//create
}//StudentDAOImpl
MainApp.java
package coreservlets;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("springConfig.xml");
StudentDAOImpl student=(StudentDAOImpl) context.getBean("studentDAOImpl");
student.create("Alessandro", new Integer(33));
}//main
}//MainApp
springConfig.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:annotation-config/>
<context:component-scan base-package="coreservlets"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_hibernate"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="10"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
</beans>
sql
create table student
(
id integer not null auto_increment,
name varchar(20) not null,
age integer not null,
primary key(id)
);
You must enable the transaction support (<tx:annotation-driven> or #EnableTransactionManagement) and declare the transactionManager and it should work through the SessionFactory.
You must add #Transactional into your #Repository
With #Transactional in your #Repository Spring is able to apply transactional support into your repository.
Your Student class has no the #javax.persistence.* annotations how #Entity, I am assuming the Mapping Configuration for that class has been defined through XML.
I have had the same issue, but in a class that was not a part of the service layer. In my case, the transaction manager was simply obtained from the context by the getBean() method, and the class belonged to the view layer - my project utilizes OpenSessionInView technique.
The sessionFactory.getCurrentSession() method, has been causing the same exception as the author's. The solution for me was rather simple.
Session session;
try {
session = sessionFactory.getCurrentSession();
} catch (HibernateException e) {
session = sessionFactory.openSession();
}
If the getCurrentSession() method fails, the openSession() should do the trick.
Add the annotation #Transactional of spring in the class service
I had this error too because in the file where I used #Transactional annotation, I was importing the wrong class
import javax.transaction.Transactional;
Instead of javax, use
import org.springframework.transaction.annotation.Transactional;
In your xyz.DAOImpl.java
Do the following steps:
//Step-1: Set session factory
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf)
{
this.sessionFactory = sf;
}
//Step-2: Try to get the current session, and catch the HibernateException exception.
//Step-3: If there are any HibernateException exception, then true to get openSession.
try
{
//Step-2: Implementation
session = sessionFactory.getCurrentSession();
}
catch (HibernateException e)
{
//Step-3: Implementation
session = sessionFactory.openSession();
}
You need to allow transaction to your DAO method.
Add,
#Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
over your dao methods.
And #Transactional should be from the package:
org.springframework.transaction.annotation.Transactional
I added these configuration in web.xml and it works well for me!
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Additionally, the most ranked answer give me clues to prevent application from panic at the first run.
My configuration was like this. I had a QuartzJob , a Service Bean , and Dao . as usual it was configured with LocalSessionFactoryBean (for hibernate) , and SchedulerFactoryBean for Quartz framework. while writing the Quartz job , I by mistake annotated it with #Service , I should not have done that because I was using another strategy to wire the QuartzBean using AutowiringSpringBeanJobFactory extending SpringBeanJobFactory.
So what actually was happening is that due to Quartz Autowire , TX was getting injected to the Job Bean and at the same time Tx Context was set by virtue of #Service annotation and hence the TX was falling out of sync !!
I hope it help to those for whom above solutions really didn't solved the issue. I was using Spring 4.2.5 and Hibernate 4.0.1 ,
I see that in this thread there is a unnecessary suggestion to add #Transactional annotation to the DAO(#Repository) , that is a useless suggestion cause #Repository has all what it needs to have don't have to specially set that #transactional on DAOs , as the DAOs are called from the services which have already being injected by #Trasancational . I hope this might be helpful people who are using Quartz , Spring and Hibernate together.
My solution was (using Spring) putting the method that fails inside another method that creates and commits the transaction.
To do that I first injected the following:
#Autowired
private PlatformTransactionManager transactionManager;
And finally did this:
public void newMethod() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus transaction = transactionManager.getTransaction(definition);
oldMethod();
transactionManager.commit(transaction);
}
#Transactional =javax.transaction.Transactional. Put it just beside #Repository.
Add transaction-manager to your <annotation-driven/> in spring-servlet.xml:
<tx:annotation-driven transaction-manager="yourTransactionBeanID"/>
Check your dao class. It must be like this:
Session session = getCurrentSession();
Query query = session.createQuery(GET_ALL);
And annotations:
#Transactional
#Repository
I encountered the same problem and finally found out that the <tx:annotaion-driven /> was not defined within the [dispatcher]-servlet.xml where component-scan element enabled #service annotated class.
Simply put <tx:annotaion-driven /> with component-scan element together, the problem disappeared.
My similar issue got fixed with below 2 approaches.
1) Through manually handling transactions:
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
UserInfo user = (UserInfo) session.get(UserInfo.class, 1);
tx.commit();
2) Tell Spring to open and manage transactions for you in your web.xml filters and Ensure to use #Repository #Transactional:
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactory</param-name>
<param-value>session.factory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In this class above #Repository just placed one more annotation #Transactional it will work. If it works reply back(Y/N):
#Repository
#Transactional
public class StudentDAOImpl implements StudentDAO
Thanks for comment of mannedear. I use springmvc and in my case I have to use as
#Repository
#Transactional
#EnableTransactionManagement
public class UserDao {
...
}
and I also add spring-context to pom.xml and it works
I had the same issue. I resolved it doing the following:
Add the this line to the dispatcher-servlet file:
<tx:annotation-driven/>
Check above <beans> section in the same file. These two lines must be present:
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation= "http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
Also make sure you added #Repository and #Transactional where you are using sessionFactory.
#Repository
#Transactional
public class ItemDaoImpl implements ItemDao {
#Autowired
private SessionFactory sessionFactory;
My Database table has mismatch column name with the Java Object (#Entity) which leads to throw the above exception.
By updating the table with appropriate column name resolves this issue.
In my case the problem was a Controller trying to access directly to a DAO with #Repository.
Adding an #Service layer on top of the #Repository fixed the problem

selective AOP invocation

I have a class on which there are several methods and the interface for the class looks something like this
Some main program calls the method doSomeOperation which in turn calls the other methods in the class based on business rule. I have a situation where I have to populate some stats after some of the methods in this class is invoked.
For example, after calling doSomeOperation which in turn calls say doOps1, populate some stats table on the database indicating how many records were inserted/updated/deleted etc in specific table and how much time it took etc by doOps1 method. I am trying to use Spring AOP for this purpose. However the issue that I am facing is that the intended code is not getting invoked.
Here is the full code (for sample purpose only)
package spring.aop.exp;
public interface Business {
void doSomeOperation();
void doOps1();
}
package spring.aop.exp;
public class BusinessImpl implements Business {
public void doSomeOperation() {
System.out.println("I am within doSomeOperation");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("Done with sleeping.");
doOps1();
}
public void doOps1() {
System.out.println("within Ops1");
}
}
The aspect class
package spring.aop.exp;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class BusinessProfiler {
#Pointcut("execution(* doOps1*(..))")
public void businessMethods1() { }
#After("businessMethods1()")
public void profile1() throws Throwable {
//this method is supposed to populate the db stats and other statistics
System.out.println("populating stats");
}
}
-- the main class
package spring.aop.exp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringAOPDemo {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"ExpAOP.xml");
Business bc = (Business) context.getBean("myBusinessClass");
bc.doSomeOperation();
}
}
*and the 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-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- Enable the #AspectJ support -->
<aop:aspectj-autoproxy />
<bean id="businessProfiler" class="spring.aop.exp.BusinessProfiler" />
<bean id="myBusinessClass" class="spring.aop.exp.BusinessImpl" />
</beans>
On running the main program, I am getting the output (and it is not calling profile1 rom the Aspect class - BusinessProfiler). however if I directly call the doOps1 from main class then the aspect method gets invoked. I would like to know if aspect is supposed to work if only called from the main method and not otherwise.
Oct 26, 2012 11:56:19 AM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext#be2358:
display name
[org.springframework.context.support.ClassPathXmlApplicationContext#be2358];
startup date [Fri Oct 26 11:56:19 EDT 2012]; root of context hierarchy
Oct 26, 2012 11:56:19 AM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions INFO: Loading XML bean definitions from class path
resource [ExpAOP.xml] Oct 26, 2012 11:56:19 AM
org.springframework.context.support.AbstractApplicationContext
obtainFreshBeanFactory INFO: Bean factory for application context
[org.springframework.context.support.ClassPathXmlApplicationContext#be2358]:
org.springframework.beans.factory.support.DefaultListableBeanFactory#1006d75
Oct 26, 2012 11:56:19 AM
org.springframework.beans.factory.support.DefaultListableBeanFactory
preInstantiateSingletons INFO: Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory#1006d75:
defining beans
[org.springframework.aop.config.internalAutoProxyCreator,businessProfiler,myBusinessClass];
root of factory hierarchy
*I am within doSomeOperation
Done with sleeping.
within Ops1***
Spring AOP is by default proxy-based and when you call a method on the same class from within another method on that calss, your call doesn't go through the aspect proxy, but directly to the method - that's why your aspect code is not invoked. To understand it better read this chapter of Spring documentation on Understanding AOP proxies.

Resources