#Component Springs annotation not working - spring

I am using Springs framework 3.2.0. and i am not able to use #component annotation. Below is the error which i received when Test.java was executed.
I tried changing the java version, and springs framework version but nothing worked.
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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="util-namespace"
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">
<context:annotation-config />
<context:component-scan base-package="com.ds.cab.car" />
<bean id="e" class="com.ds.cab.engine.Engine">
<property name="modelyear" value="2015 AUDI"></property>
</bean>
</beans>
Car.java
package com.ds.cab.car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ds.cab.engine.Engine;
#Component
public class Car {
#Autowired
private Engine engine;
public void setEngine(Engine engine) {
this.engine = engine;
}
public void printData() {
// TODO Auto-generated method stub
System.out.println("Engine model year: "+engine.getModelyear());
}
}
Engine.java
package com.ds.cab.engine;
public class Engine {
private String modelyear;
public void setModelyear(String modelyear) {
this.modelyear = modelyear;
}
public String getModelyear() {
return modelyear;
}
}
Test.java
package ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ds.cab.car.Car;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
Car c = (Car)ctx.getBean(Car.class);
c.printData();
}
}
Error
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [E:\Prakhar\STS Workspace\StereoTyping01\bin\com\ds\cab\car\Car.class]; nested exception is java.lang.IllegalArgumentException
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:281)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242)
at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1435)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1425)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:184)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at ioc.Test.main(Test.java:10)
Caused by: java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:257)
... 24 more

Create a Car bean and inject your engine bean into it (e represents your engine bean name):
<bean id="Car" class = "com.ds.cab.car.Car">
<constructor-arg ref="e"/>
</bean>

In your beans.xml,
Change component-scan into
<context:component-scan base-package="com.ds.cab.car" />
Remove engine bean declarion.
Add #Component annotation to Car Class.

Related

How to get DataSource bean from config in the Junit5

Dears,
I have created a junit5 test case ( UserDaoTests.java) but I am not able to get DataSource Bean defined in the spring configuration file (data.xml).
Project Structure:
test cases are defined in test/com/caveofprogramming/spring/test/tests package, UserDaoTests.java class.
data.xml
configuration file for junit. I have defined datasource bean in it.
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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.3.xsd">
<context:component-scan
base-package="com.caveofprogramming.spring.test.tests">
</context:component-scan>
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<context:property-placeholder
location="test/com/caveofprogramming/spring/test/config/jdbc.properties" />
<beans profile="dev">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
</beans>
</beans>
jdbc.properties:
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = TESTD01)))
jdbc.password=1234
jdbc.username=offerTest
Junit test(UserDaoTests.java)
package com.caveofprogramming.spring.test.tests;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import com.offers.DAO.UserDAO;
#ActiveProfiles("dev")
#ContextConfiguration(locations = {
"classpath:test/com/caveofprogramming/spring/test/config/data.xml",
"classpath:com/offers/config/offerDAO-context.xml",
"classpath:com/offers/config/offerService-context.xml" })
public class UserDaoTests {
#Autowired
private UserDAO userDao;
private static DataSource dataSource;
private JdbcTemplate jdbc;
#Autowired
public UserDaoTests() {
ApplicationContext context = new FileSystemXmlApplicationContext("test/com/caveofprogramming/spring/test/config/data.xml");
this.dataSource = (DataSource) context.getBean("dataSource");
}
#Test
public void testCreateUser() {
if ( dataSource == null) {
System.out.println("DataSource is null");
}
else {
System.out.println("DataSource is not null!!!! ");
}
}
}
Logs:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:816)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1288)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
I would also like to clarify that I am using static DataSource because I need to use #BeforeAll, which require static fields only.
I have tested for non static Data Source as well but result is still the same.
--Update----
I removed <beans profile="dev"> tag from data.xml config file and it's working fine. But I don't understand why it's not working with profile.
--- Update 2 ( Update on on Bhushan's answer) -----
UserDaoTests - updated code
#ExtendWith(SpringExtension.class)
//Add all required depency xml
#ContextConfiguration(locations = { "classpath:test/com/caveofprogramming/spring/test/config/data.xml",
"classpath:com/offers/config/offerDAO-context.xml",
"classpath:com/offers/config/offerService-context.xml" })
#ActiveProfiles("dev")
public class UserDaoTests {
#Autowired
private UserDAO userDao;
#Autowired
private DataSource dataSource;
#Autowired
private JdbcTemplate jdbc;
#Test
public void testCreateUser() {
Assertions.assertNotNull(dataSource);
// Assertions.assertNotNull(jdbc);
}
}
Error Stacktrace:
org.opentest4j.AssertionFailedError: expected: not <null>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
at org.junit.jupiter.api.Assertions.fail(Assertions.java:109)
at org.junit.jupiter.api.AssertNotNull.failNull(AssertNotNull.java:47)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:36)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:31)
at org.junit.jupiter.api.Assertions.assertNotNull(Assertions.java:283)
at com.caveofprogramming.spring.test.tests.UserDaoTests.testCreateUser(UserDaoTests.java:38)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:141)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Here you are creating multipe application context, one is creating with #ContextConfiguration and another one with FileSystemXmlApplicationContext, so avoid FileSystemXmlApplicationContext and update your code following
#ExtendWith(SpringExtension.class)
//Add all required depency xml
#ContextConfiguration(locations = {
"classpath:test/com/caveofprogramming/spring/test/config/data.xml",
"classpath:com/offers/config/offerDAO-context.xml",
"classpath:com/offers/config/offerService-context.xml" })
#ActiveProfiles("dev")
public class UserDaoTests {
#Autowired
private UserDAO userDao;
#Autowired
private DataSource dataSource;
#Autowired
private JdbcTemplate jdbc;
#Test
public void testCreateUser() {
Assertions.assertNotNull(dataSource);
Assertions.assertNotNull(jdbc);
}
}
Also avoid #BeforeAll as its coupled with static memory, and ours Beans are managed by spring so can't go with it, instead of it you can you for #BeforeEach and if you want perform some logic witch you want run only once for all test cases so you can do hack something like
private AtomicBoolean executed = new AtomicBoolean(false);
#BeforeEach
public void runOnce() {
if(!executed.getAndSet(true)) {
// write you logic which you want will run only once for all test cases
}
}

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.

No default constructor found; nested exception is java.lang.NoSuchMethodException

It throws NoSuchMethodException while deploying, constructor param is already set in xml config file though.
What am i missing? Git repo is here
Regards
security-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:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.trafficalarm.rest.security" />
<bean id="roleHierarchy"
class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
<property name="hierarchy">
<value>
ROLE_ADMIN > ROLE_USER
ROLE_USER > ROLE_GUEST
</value>
</property>
</bean>
<bean id="roleVoter" class="com.trafficalarm.rest.security.HierarchicalJsr250Voter">
<constructor-arg ref="roleHierarchy" />
</bean>
<!-- Access voters -->
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
</list>
</property>
</bean>
<sec:global-method-security jsr250-annotations="enabled" access-decision-manager-ref="accessDecisionManager"/>
<oauth:expression-handler id="oauthExpressionHandler"/>
<oauth:web-expression-handler id="oauthWebExpressionHandler"/>
</beans>
HierachicalJsr250Voter.java
package com.trafficalarm.rest.security;
import java.util.Collection;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.annotation.Jsr250SecurityConfig;
import org.springframework.security.access.annotation.Jsr250Voter;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
//import org.springframework.util.Assert;
#Component
public class HierarchicalJsr250Voter extends Jsr250Voter {
private RoleHierarchy roleHierarchy = null;
public HierarchicalJsr250Voter(RoleHierarchy roleHierarchy) {
//Assert.notNull(roleHierarchy, "RoleHierarchy must not be null");
this.roleHierarchy = roleHierarchy;
}
#Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> definition) {
boolean jsr250AttributeFound = false;
for (ConfigAttribute attribute : definition) {
if (Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE.equals(attribute)) {
return ACCESS_GRANTED;
}
if (Jsr250SecurityConfig.DENY_ALL_ATTRIBUTE.equals(attribute)) {
return ACCESS_DENIED;
}
if (supports(attribute)) {
jsr250AttributeFound = true;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : extractAuthorities(authentication)) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN;
}
Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
return roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities());
}
}
Exception stacktrace is
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hierarchicalJsr250Voter' defined in file [F:\yildirimBck\sts-bundle\pivotal-tc-server-developer-3.0.0.RELEASE\base-instance\wtpwebapps\trafficalarm\WEB-INF\classes\com\trafficalarm\rest\security\HierarchicalJsr250Voter.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.trafficalarm.rest.security.HierarchicalJsr250Voter]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.trafficalarm.rest.security.HierarchicalJsr250Voter.<init>()
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:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4760)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5184)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:581)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1686)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.trafficalarm.rest.security.HierarchicalJsr250Voter]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.trafficalarm.rest.security.HierarchicalJsr250Voter.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 26 more
Caused by: java.lang.NoSuchMethodException: com.trafficalarm.rest.security.HierarchicalJsr250Voter.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
... 27 more
Apr 07, 2015 6:20:26 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Remove #Component from your Hierarchical Voter class.
#Component will try to automatically instantiate your class via the component scan and because you haven't #Autowired your dependency, it cannot inject it when it tries to instantiates your class as part of the <context:component-scan>. This happens before Spring tries to instantiate your bean via xml...
If you are using the Spring Security 4, then you should use:
<constructor-arg ref="roleVoter"/>
For bean accessDecisionManager. So, it should be like:
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<constructor-arg ref="roleVoter"/>
</bean>

Autowiring Controller doesn't work after adding entityManagerFactory bean

I've wrote a spring mvc webserver which uses NEO4j as data backend. Now i want to expand this with cassandra, so the server should be able to use both databases.
I have followed these 2 tutorials on how to combine Kundera (A JPA based Cassandra API):
https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Spring
https://code.google.com/p/kundera/wiki/HowToUseKunderaWithSpring
But i'm not able to add the entitymanagerfactory bean to my applicationcontext.xml file.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
When i do this, spring gives an error that it can not create any of the already existing controllers that my webserver uses.
Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 22 more
Those controllers are created by using the #Controller annotation in their class files and by autowiring them in the files where they are used. This works fine normally but when i add the entityManagerFactory bean it suddenly stops working. How is this possible?
My applicationContext file currently looks like this:
<?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:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans. For example #Controller and #Service. -->
<context:component-scan base-package="bmsapp" />
<!-- Activate Spring Data Neo4j repository support -->
<neo4j:config storeDirectory="data/graph.db" base-package="bmsapp.domain" />
<neo4j:repositories base-package="bmsapp.repository" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
<tx:annotation-driven mode="proxy" />
<!-- context:annotation-config / -->
<!-- use this for Spring Jackson JSON support -->
<mvc:annotation-driven />
And my persistence.xml file:
<persistence 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"
version="2.0">
<persistence-unit name="cassandra_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost"/>
<property name="kundera.port" value="9160"/>
<property name="kundera.keyspace" value="KunderaExamples"/>
<property name="kundera.dialect" value="cassandra"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.cassandra.pelops.PelopsClientFactory" />
<property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider"/>
<property name="kundera.cache.config.resource" value="/ehcache-test.xml"/>
</properties>
</persistence-unit>
SimpleComment domain class:
package bmsapp.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "SIMPLE_COMMENT", schema = "KunderaExamples#cassandra_pu")
#XmlRootElement(name = "SimpleComment")
public class SimpleComment {
#Id
#Column(name = "COMMENT_ID")
private int id;
#Column(name = "USER_NAME")
private String userName;
#Column(name = "COMMENT_TEXT")
private String commentText;
public SimpleComment() {
}
public SimpleComment(int commentId, String userName, String commentText) {
this.id = commentId;
this.userName = userName;
this.commentText = commentText;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
}
SpringExampleDao:
package bmsapp.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import bmsapp.domain.SimpleComment;
#Service
public class SpringExampleDao
{
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;
public SimpleComment addComment(int id, String userName, String commentText)
{
SimpleComment simpleComment = new SimpleComment(id, userName, commentText);
entityManager.persist(simpleComment);
return simpleComment;
}
public SimpleComment getCommentById(String Id)
{
SimpleComment simpleComment = entityManager.find(SimpleComment.class, Id);
return simpleComment;
}
public List<SimpleComment> getAllComments()
{
Query query = entityManager.createQuery("SELECT c from SimpleComment c");
List<SimpleComment> list = query.getResultList();
return list;
}
}
The relevant part of the stacktrace is:
nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
So you need to add a dependency to spring-orm, see http://mvnrepository.com/artifact/org.springframework/spring-orm.
However, I'm not sure that really solves your problem. In the description you're mentioning Neo4j and I cannot see what part of your description relates to that.

#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