#AspectJ Based AOP with Spring 3.1 - spring

I am trying to run a #AspectJ Based AOP with Spring 3.1 & not able to configure pointcut properly
Pointcut and advice methods are :
Pointcuts:
#Pointcut("execution(* point.*.*(..))")
public void selectAll() {}
after advice:
#After("selectAll()")
public void afterAdvice() {
System.out.println("profile has been setup.");
}
before advice:
#Before("selectAll()")
public void beforeAdvice() {
System.out.println("Going to setup profile.");
}
& run main program i got Exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'student' defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut selectAll
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
although when i give pointcut expression in beforeAdvice() and afterAdvice() methods , remove PointCuts method every thing work fine
#Before("execution(* point.*.*(..))")
public void beforeAdvice() {
System.out.println("Going to setup profile.");
}
#After("execution(* point.*.*(..))")
public void afterAdvice() {
System.out.println("profile has been setup.");
}
i am trying to apply pointcut to method of Student class:
package point;
public class Student{
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age);
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name);
return name;
}
public void printThrowException() {
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
spring configuration 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: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 ">
<aop:aspectj-autoproxy />
<bean id="student" class="point.Student">
<property name="name" value="Zara" />
<property name="age" value="11" />
</bean>
<bean id="logging" class="point.Logging" />
</beans>
Jar file used :
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.6.8.jar
aspectjtools-1.5.4.jar
aspectjweaver-1.6.2.jar
cglib-2.2.2.jar
with spring 3.1 jar's

solved the problem : The issue while creating bean was because of old jars
Replaced jars:
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.6.8.jar
aspectjtools-1.5.4.jar
aspectjweaver-1.6.2.jar
cglib-2.2.2.jar
with
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.7.0.jar
aspectjweaver-1.7.0.jar
cglib-2.2.2.jar

Related

Error creating bean with name 'xxx'

I'm having issues with dependency injection.
I've tried both #EJB and #Autowired, but nothing works.
This is what i have now:
HomeController
#Controller
#ComponentScan(basePackages = "org.vives.repositories")
public class HomeController extends HttpServlet {
private final BeerRepository beerRepository;
#Autowired
public HomeController(BeerRepository beerRepository) {
this.beerRepository = beerRepository;
}
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = this.beerRepository.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}
When I hover over beerRepository parameter, I get that:
BeerRepository
#Stateless
#Repository
public class BeerRepository {
#PersistenceContext(unitName = "vivesPU")
private EntityManager entityManager;
public List<Brewer> getAll() {
List<Brewer> brewers = new ArrayList<>();
Brewer br0 = new Brewer("WESTVLETEREN BREWERY");
Brewer br1 = new Brewer("BRASSERIE CANTILLON");
Brewer br2 = new Brewer("RODENBACH BREWERY");
Brewer br3 = new Brewer("KULMINATOR");
Brewer br4 = new Brewer("‘T BRUGS BEERTJE");
brewers.add(br0);
brewers.add(br1);
brewers.add(br2);
brewers.add(br3);
brewers.add(br4);
return brewers;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="vivesPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/beers</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Error log (some of it)
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController' defined in file [..\HomeController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beerRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beerRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available
...
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available]]
vivesPU is the persistance-unit name, so why would it even go there?
project structure
Can someone explain to me what is happening? I'm really confused. Most of the documentation and posts are old (Spring 4 and Spring XML) which are barely relevant.
Either you have to autowire BeerRepository or remove the below line
private final BeerRepository beerRepository;
Your controller is completely false. It should be
#Controller
#ComponentScan(basePackages = "org.vives.repositories")
public class HomeController extends HttpServlet {
#Autowired
private BeerRepository beerRepository;
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = beerRepository.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}

Inject EJB 3.0 in spring 2.0 controller on websphere is throwing exception

I'd like to call an EJB service from my spring bean. I have tried many ways like the below and deployed on websphere, but it gives me exception in jndi names. Can anyone help?
Spring 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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<bean id="ejbService" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName" value="ejb/EjbServiceImpl"/>
<property name="businessInterface" value="com.services.EjbService"/>
</bean>
<bean id="springController" class="com.controllers.SpringController" scope="session">
<property name="eService" ref="ejbService"/>
</bean>
</beans>
Spring controller
public class SpringController {
private EjbService eService;
public void setOrders(Order order) {
eService.liquidPortfolio(order);
}
public EjbService getEService() {
return eService;
}
public void setEService (
EjbService eService) {
this.eService = eService;
}
}
EJB
#Local
public class EjbService {
#Asynchronous
public void setOrders(Order order) ;
}
#Stateless
#Singleton
public class EjbServiceImpl implements EjbService{
#PostConstruct
public void init() {
System.out.println(" init method");
}
#Asynchronous
public void setOrders(Order order) {
System.out.println(" order=" + order);
}
}
Exception
[4/3/16 9:44:30:708 AST] 0000007a ContextLoader E org.springframework.web.context.ContextLoader initWebApplicationContext Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ejbService' defined in ServletContext resource [/WEB-INF/my-web-context.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Context: WSRUHHQ830Node01Cell/nodes/WSRUHHQ830Node01/servers/server1, name: ejb/EjbServiceImpl: First component in name EjbServiceImpl not found. [Root exception is org.omg.CosNaming.NamingContextPackage.NotFound: IDL:omg.org/CosNaming/NamingContext/NotFound:1.0]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
Caused by: javax.naming.NameNotFoundException: Context: WSRUHHQ830Node01Cell/nodes/WSRUHHQ830Node01/servers/server1, name: ejb/EjbServiceImpl: First component in name EjbServiceImpl not found. [Root exception is org.omg.CosNaming.NamingContextPackage.NotFound: IDL:omg.org/CosNaming/NamingContext/NotFound:1.0]
at com.ibm.ws.naming.jndicos.CNContextImpl.mapNotFoundException(CNContextImpl.java:4564)
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1822)
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1777)
at com.ibm.ws.naming.jndicos.CNContextImpl.lookupExt(CNContextImpl.java:1434)
at com.ibm.ws.naming.jndicos.CNContextImpl.lookup(CNContextImpl.java:616)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:165)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:179)
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
at javax.naming.InitialContext.lookup(InitialContext.java:423)
Caused by: org.omg.CosNaming.NamingContextPackage.NotFound: IDL:omg.org/CosNaming/NamingContext/NotFound:1.0
at com.ibm.ws.naming.ipcos.WsnOptimizedNamingImpl.do_resolve_complete_info(WsnOptimizedNamingImpl.java:567)
at com.ibm.ws.naming.cosbase.WsnOptimizedNamingImplBase.resolve_complete_info(WsnOptimizedNamingImplBase.java:2169)
at com.ibm.WsnOptimizedNaming._NamingContextStub.resolve_complete_info(_NamingContextStub.java:538)
at com.ibm.ws.naming.jndicos.CNContextImpl$2.run(CNContextImpl.java:2958)
at com.ibm.ws.naming.jndicos.CNContextImpl$2.run(CNContextImpl.java:2954)
at com.ibm.ws.naming.util.CommonHelpers.retry(CommonHelpers.java:871)
at com.ibm.ws.naming.jndicos.CNContextImpl.cosResolve(CNContextImpl.java:2952)
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1818)
thanks for all whom trying help me, actually solved my problem in the following way
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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<bean id="springController" class="com.controllers.SpringController" scope="session">
<property name="eService" ref="ejbService"/>
</bean>
<jee:jndi-lookup id="ejbService" jndi-name="java:global/myEAR/myApp/EjbService">
</jee:jndi-lookup>
</beans>
Spring controller
public class SpringController {
private EjbService eService;
public void setOrders(Order order) {
eService.liquidPortfolio(order);
}
public EjbService getEService() {
return eService;
}
public void setEService (
EjbService eService) {
this.eService = eService;
}
}
MY EJB
#LocalBean
#Stateless
#Singleton
public class EjbService {
#Asynchronous
public void setOrders(Order order) {
System.out.println(" order=" + order);
}
}

Spring:Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]

I am new new to spring programming.While executing a program for fetching some records from mysql database i am getting these errors:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'jtemplate' while setting bean property 'jdbcTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jtemplate' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at Test.main(Test.java:15)
I have three files in my project.
1.EmpDAO.java:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class EmpDAO {
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudents(){
return (List<Student>) template.query("select * from test",new ResultSetExtractor(){
#Override
public List<Student> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Student> list=new ArrayList<Student>();
while(rs.next()){
Student e=new Student();
e.setName(rs.getString(1));
e.setRoll(rs.getString(2));
list.add(e);
}
return list;
}
});
}
}
2.Student.java:
public class Student {
private String name;
private String roll;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void display(){
System.out.println("Name: "+name+" Roll="+roll);
}
}
3.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmpDAO">
<property name="jdbcTemplate" ref="jtemplate"></property>
</bean>
</beans>
4.Test.java(for execution):
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
EmpDAO dao=(EmpDAO)factory.getBean("edao");
List<Student> list=dao.getAllStudents();
for(Student e:list)
System.out.println(e);
}
}
The jars that i included in reference library:
These are the jars i included
Kindly help me in this regards.A prevalentines day thank you is in advance.
The relevant part of your errormessage is:
java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
You can download that jar from here: 5.1.38, or look for different versions on the central nexus repository.
Note: you would be much better of employing some dependency management system, rather than doing this manually. I suggest taking a look at Maven.

BeanCreationException: Error creating bean with name 'EmpInfo'

[HTTP:101216]Servlet: "cxf" failed to preload on startup in Web application: "TestSpring-0.0.1-SNAPSHOT.war". org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmpInfo': Invocation of init method failed; nested exception is javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403) at
My cxf.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:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<!-- <jaxws:endpoint id="EmpInfo"
implementor="#EmpInfoImpl"
address="/EmpInfo"/> -->
<jaxws:endpoint id="EmpInfo"
implementor="com.test.example.impl.EmpInfoImpl"
address="/EmpInfo"/>
<!-- <bean id="EmpInfoImpl" class="com.test.example.impl.EmpInfoImpl" >
<property name="emplist" ref="EmpList" />
</bean>
<bean id="EmpList" class="com.test.example.impl.EmployeeList" /> -->
</beans>
#WebService(serviceName="EmpInfo",endpointInterface="com.test.example.EmpInfo",
portName="EmpInfoPortType", wsdlLocation="classpath:wsdl/EmpInfo.wsdl")
public class EmpInfoImpl implements EmpInfo{
private EmployeeList emplist;
public EmployeeList getEmplist() {
return emplist;
}
public void setEmplist(EmployeeList emplist) {
this.emplist = emplist;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public Employee getInfo(String id) {
// TODO Auto-generated method stub
return new Employee("Test","Test","888");
//return emplist.getEmp(Integer.valueOf(id));
}
}
I am pretty new to CXF , so any help will be highly appreciated
This issue is resolved there was a issue in my code.

#Transactional cause nosuchbeandefinitionexception in spring framework

I have a problem when annotating with #transactional a method of my service class. Such annotation cause a NoSuchBeanDefinitionExcpetion in my test class where the service class is autowired. If the transactional annotation is removed it works fine again. Why is this happening, I couldn't find a clue in spring documentation.
This is my application-context.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.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="<mypackage...>" />
<import resource="data-context.xml"/>
<import resource="resources-context.xml"/>
<import resource="persistence-context.xml"/>
This is part of my persistence-context.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/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceConnection" />
<property name="configLocation"
value="classpath:configuration/mybatis/config.xml"></property>
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceConnection" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="accessDao" class="dao.impl.AccessDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="utilitiesDao" class="dao.impl.UtilitiesDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="portafoglioDao" class="dao.impl.PortafoglioDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
part of my test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:configuration/applicationContext.xml" })
public class MyTest {
#Autowired
ApplicationContext context;
#Autowired
DriverManagerDataSource dataSourceConnection;
#Autowired
AccessAppDelegate accessApp;
the class that generates the problem
#Service
public class AccessAppDelegate extends Delegate implements DelegateInterface {
private PersonalCodesManager pcm;
AccessApp accessReq;
#Override
#Transactional
public void elaborateRequestImpl() throws Exception {
accessReq = (AccessApp) requestBean;
if (accessReq.getLan() != null) {
lang = StringUtilities.toLan(accessReq.getLan());
accessDao.updateDeviceLanguage(accessReq.getUser().getImei(),
accessReq.getLan());
}
if (requestWrap.getRequestType().compareTo(
ApplicativeConsts.INTESTAZIONE_REQUEST_LOGIN) == 0)
elaborateRequestLogin();
else
elaborateRequestAttivazione();
}
some private methods...
public PersonalCodesManager getPcm() {
return pcm;
}
public void setPcm(PersonalCodesManager pcm) {
this.pcm = pcm;
}
#Override
public String getUserId() {
accessReq = (AccessApp) requestBean;
return accessReq.getUser().getId();
}
#Override
public Class getRequestType() {
return AccessApp.class;
}
}
the class Delegate
#Component
public class Delegate{
String jsonReq;
String jsonRes;
#Autowired
ApplicationContext ctx;
#Autowired
AccessDao accessDao;
Locale lang;
java.sql.Timestamp timestamp;
RequestWrapper requestWrap;
UserAndDeviceTable userInfo;
AuthUserTable auth;
BaseResponse responseBean;
BaseRequest requestBean;
public void elaborateRequest(String body,boolean authenticationRequired){
DelegateInterface endpointImplementation = (DelegateInterface) this;
timestamp = new java.sql.Timestamp(new java.util.Date().getTime());
if (body.startsWith("json=")){
body = body.split("json=")[1];
}
requestWrap = new RequestWrapper(body);
requestBean=requestWrap.getReq(endpointImplementation.getRequestType());
this.jsonReq = requestWrap.getRequestBody();
lang = StringUtilities.toLan("en");
try {
if (authenticationRequired) {
auth = this.accessDao.checkSessioneAperta(requestBean.getSessionID(), timestamp);
if(auth==null) {
throw new Exception("Unauthorized Access");
}else{
setUserInfo(auth.getEmail());
}
}else{
setUserInfo(endpointImplementation.getUserId());
}
if(userInfo!=null){
lang=StringUtilities.toLan(userInfo.getLanguage());
}
endpointImplementation.elaborateRequestImpl();
} catch (Exception e) {
responseBean= new BaseResponse(String.valueOf(ApplicativeConsts.RC_ERRORE),ctx.getMessage(ApplicativeConsts.MSG_ERRORE_GENERAL, null, lang));
e.printStackTrace();
}
try {
ObjectMapper mapper = new ObjectMapper();
this.jsonRes = mapper.writeValueAsString(responseBean);
} catch (Exception e) {
e.printStackTrace();
}
}
public ModelMap getResponse(ModelMap model) {
// TODO Auto-generated method stub
model.addAttribute(ApplicativeConsts.INTESTAZIONE_RESPONSE, responseBean);
return model;
}
public void setUserInfo(String email) {
List<UserAndDeviceTable> userList = accessDao.findUserAndDeviceTableByEmail(email);
if (userList.size()==1){
this.userInfo = userList.get(0);
}
}
public String getJsonReq() {
return jsonReq;
}
public String getJsonRes() {
return jsonRes;
}
public BaseResponse getResponseBean() {
return responseBean;
}
}
the interface
public interface DelegateInterface {
public void elaborateRequestImpl() throws Exception;
public ModelMap getResponse(ModelMap response);
public String getUserId();
public Class getRequestType();
}
The exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TestClass': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.something.be.delegates.AccessAppDelegate it.something.controller.somethingControllerTestAuto.accessApp; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [it.something.be.delegates.AccessAppDelegate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.something.be.delegates.AccessAppDelegate it.something.controller.somethingControllerTestAuto.accessApp; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [it.something.be.delegates.AccessAppDelegate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [it.something.be.delegates.AccessAppDelegate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
This is because you are requesting spring to auto wire to a field which is not an interface. Adding #Transactional results in your object being wrapped in a proxy - the proxy will implement all the interfaces implemented by the class. It can be auto wired to fields of the interface type only. Change the below field definition in your test to the corresponding interface to fix the issue.
#Autowired
AccessAppDelegate accessApp;

Resources