Spring 3 AOP and Mongo DB Integration - java

I was using Mongo DB with Spring Data, everything was working fine until I decided to use Spring AOP Aspects for the logging purpose. Here is my spring configuration, Person Service and LoggingAspect Code:
<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:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.vaap" />
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="rakeshdb" mongo-ref="mongo"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="personService" class="com.vaap.PersonService"></bean>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="loggingAspect" class="com.vaap.aop.LoggingAspect" />
</beans>
package com.vaap;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
public class PersonService implements IPersonService {
#Autowired
MongoTemplate mongoTemplate;
public static final String COLLECTION_NAME = "person";
public void addPerson(Person person) {
if (!mongoTemplate.collectionExists(Person.class)) {
mongoTemplate.createCollection(Person.class);
}
person.setId(UUID.randomUUID().toString());
// mongoTemplate.save(objectToSave, collectionName);
// DBObject dbObject = (DBObject) JSON.parse(jsonStr);
mongoTemplate.insert(person, COLLECTION_NAME);
}
public List<Person> listPerson() {
return mongoTemplate.findAll(Person.class, COLLECTION_NAME);
}
public String getPersonJSON() {
BasicQuery basicQuery = new BasicQuery("{'status':'Active'}");
return mongoTemplate.find(basicQuery, String.class, COLLECTION_NAME)
.toString();
}
public void deletePerson(Person person) {
mongoTemplate.remove(person, COLLECTION_NAME);
}
public void updatePerson(Person person) {
mongoTemplate.insert(person, COLLECTION_NAME);
}
}
package com.vaap.aop;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
#Component
#Configurable
#Aspect
public class LoggingAspect {
static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);
#AfterThrowing(pointcut = "execution(* *.*(..))", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
log.error("An exception has been thrown in "
+ joinPoint.getSignature().getName() + "()");
log.error("Cause :" + e.getCause());
}
#Around("execution(* *.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("The method " + joinPoint.getSignature().getName()
+ "() begins with " + Arrays.toString(joinPoint.getArgs()));
try {
Object result = joinPoint.proceed();
log.info("The method " + joinPoint.getSignature().getName()
+ "() ends with " + result);
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument "
+ Arrays.toString(joinPoint.getArgs()) + " in "
+ joinPoint.getSignature().getName() + "()");
throw e;
}
}
}
If I comment <aop:aspectj-autoproxy proxy-target-class="true"/> line everything works fine otherwise I am getting this error:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mongoTemplate' defined in class path resource [SpringConfig.xml]:
Cannot resolve reference to bean 'mongoDbFactory' while setting constructor argument;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mongoDbFactory': Initialization of bean failed;
nested exception is org.springframework.aop.framework.AopConfigException:
Could not generate CGLIB subclass of class [class org.springframework.data.mongodb.core.SimpleMongoDbFactory]:
Common causes of this problem include using a final class or a non-visible class;
nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments
I know, it may not be spring problem as this is standard CGI Lib behaviour but what alternatives do I have if I want to go with XML configuration and want to use both, spring data with mongodb and spring aop for logging.

Related

Spring 4, #Resource annotated field is null

I have class AnnotatedCollectionInjection with #Resource annotated fields:
package LearnBook.part0.s9;
import LearnBook.Common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
#Service("injectedAnnotatedCollection")
public class AnnotatedCollectionInjection {
#Resource(name = "map")
private Map<String, String> map;
#Resource(name = "props")
private Properties props;
#Resource(name = "set")
private Set<Integer> set;
#Resource(name = "list")
private List<Long> list;
#Override
public String toString() {
return "CollectionInjection{\n" +
"map=" + map +
", \nprops=" + props +
", \nset=" + set +
", \nlist=" + list +
"\n}";
}
public static void main(String ...args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"META-INF/spring/learnbook/part0/s9/a1.xml"
);
System.out.println(ctx.getBean("injectedAnnotatedCollection"));
}
}
Spring configuration (a1.xml) is here:
<?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:util="http://www.springframework.org/schema/util"
xmlns:c="http://www.springframework.org/schema/c"
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/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config/>
<context:component-scan base-package="LearnBook.part0.s9"/>
<util:map id="map" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
<entry key="someValue" value="is value"/>
<entry key-ref="someKeyValue" value-ref="someStringValue"/>
</util:map>
<util:properties id="props">
<prop key="one">two</prop>
<prop key="DA">DO</prop>
</util:properties>
<util:list id="list" value-type="java.lang.Long">
<ref bean="someLongValue"/>
<value>2000</value>
</util:list>
<util:set id="set" value-type="java.lang.Integer">
<ref bean="someIntValue"/>
<value>200</value>
</util:set>
<bean id="someStringValue"
class="java.lang.String"
c:_0="Some string value"/>
<bean id="someKeyValue"
class="java.lang.String"
c:_0="Some key value"/>
<bean id="someLongValue"
class="java.lang.Long"
c:_0="25"/>
<bean id="someIntValue"
class="java.lang.Integer"
c:_0="7"/>
</beans>
But field is null, why?:
CollectionInjection{
map=null,
props=null,
set=null,
list=null
}
If i create setter and move annotation to it, i haven't get changes (map field also is null):
private Map<String, String> map;
#Resource(name = "map")
public void setMap(Map<String, String> map) {
this.map = map;
}
Your configuration looks fine as long as the file is present in the class path given META-INF/spring/learnbook/part0/s9/a1.xml.
Just ran the test by lowering the package name as learnBook.part0.s9, <context:component-scan base-package="learnBook.part0.s9"/> and with FileSystemXmlApplicationContext instead of ClassPathXmlApplicationContext
public static void main(String ...args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"C://fullyQualifiedPathTo//a1.xml"
);
System.out.println(ctx.getBean("injectedAnnotatedCollection"));
}
Received the output successfully.
CollectionInjection{
map={someValue=is value, Some key value=Some string value},
props={one=two, DA=DO},
set=[7, 200],
list=[25, 2000]
}

Cron expression must consist of 6 fields(found 1 in "${cron.expression}) partially fixed but having issues with AnnotationConfigApplicationContext

I am trying to parameterize cron expression and reading it from properties file. During this process I get following exception "Error creating bean with name 'springScheduleCronExample': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid #Scheduled method 'cronJob': Cron expression must consist of 6 fields (found 1 in "${cron.expression}")".
Then I found following post
Using that I cron expression is being read, only if I have
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
define in my main method. The issue that I am having is, I want to run this on server without main method, can anyone please help me with this.
Here is my 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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<util:properties id="applicationProps" location="application.properties" />
<context:property-placeholder properties-ref="applicationProps" />
<bean class="com.hemal.spring.SpringScheduleCronExample" />
</beans>
My SpringScheduleCronExample.java looks like this
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
#Configuration
#EnableScheduling
#PropertySource("classpath:application.properties")
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job # cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
My application Properties has
cron.expression=*/5 * * * * ?
Here is how I got it to work
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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:property-placeholder properties-ref="applicationProps" />
<context:annotation-config/>
<context:component-scan base-package="com.hemal.spring" />
<task:annotation-driven />
</beans>
MyApplicationConfig.java
package com.hemal.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
#Configuration
#EnableScheduling
#ComponentScan(basePackages = {"com.hemal.spring"})
#PropertySource("classpath:application.properties")
public class MyApplicationConfig {
#Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new ClassPathResource( "application.properties" ));
properties.setIgnoreResourceNotFound(false);
return properties;
}
}
MyApplicationContext.java
package com.hemal.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class MyApplicationContext implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MyApplicationConfig.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
}
}
My scheduler class
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job # cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
application.properties
cron.expression=0/5 * * * * ?

Failed to load ApplicationContext while running test cases

when i am running my spring integration junit class i am getting above exception.
here is my class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BpmControllerTest {
#Autowired
private BpmProcessorDaoImplTest bpmProcessorDao;
#Test
public void testRun() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
List<User>user=bpmProcessorDao.testRead();
Assert.assertEquals(0,user.size());
}
}
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
here is my stack trace..
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 37 more
can any body please tell me how to write this line
#ContextConfiguration(locations = "classpath:applicationContext.xml")
some places in google i found like this
#ContextConfiguration(locations = "classpath:**/applicationContext.xml")
what is the difference of these two
and when i am writing this line with stars i am getting different exception
here is my stack trace.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.tcs.test.dao.BpmProcessorDaoImplTest] 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:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 28 more
and one thing that my application is only dynamic web project no maven,no ant .
can any body please tell me how to run my test cases successfully..
here is my applicationContext.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
">
<tx:annotation-driven />
<tx:jta-transaction-manager/>
<context:component-scan base-package="com.tcs.test" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.19.8.159:1521/OIM.itba.gov.in" />
<property name="username" value="AppDB"></property>
<property name="password" value="AppDB"></property>
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="runScheduler" class="com.tcs.controller.BpmControllerTest" />
<task:scheduled-tasks>
<task:scheduled ref="runScheduler" method="testRun" cron="0 0/1 * * * ?" />
</task:scheduled-tasks>
</beans>
all my test java files in side test source folder.
and all the files in side the package's which prefix is com.tcs.test
here is my daoImpl class
package com.tcs.test.dao;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import com.tcs.controller.BPMConstants;
import com.tcs.controller.User;
#Repository
public class BpmProcessorDaoImplTest implements BpmProcessorDaoTest{
private static final Logger logger=Logger.getLogger(BpmProcessorDaoImplTest. class);
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
#Test
public void testWrite() {
}
#Test
public void testUpdateStatus() {
}
#Test
public List<User> testRead() {
String query=null;
List<User>users=null;
try{
// jdbcTemplate.setDataSource(dataSource);
// query=messageSource.getMessage(BPMConstants.QUERY,null,Locale.US);
query="select taskoutcome,seqNo,hash_mapdata,userid,status,taskId from com_tt_bpm_batch , "
+ "wftask where status='ACTIVE' and request_id=instanceid and state='ASSIGNED'";
logger.info("query");
jdbcTemplate.setFetchSize(20);
users=jdbcTemplate.query(query, new ResultSetExtractor<List<User>>(){
List<User> userList = new ArrayList<User>();
#SuppressWarnings("unchecked")
#Override
public List<User> extractData(ResultSet rs) throws SQLException,DataAccessException {
while(rs.next()){
logger.info("fetching records from db");
User user = new User();
user.setTaskOutcome(rs.getString(BPMConstants.TASK_OUTCOME));
user.setUserId(rs.getString(BPMConstants.USER_ID));
user.setStatus(rs.getString(BPMConstants.STATUS));
user.setTaskId(rs.getString(BPMConstants.TASK_ID));
user.setSeqNo(rs.getLong(BPMConstants.SEQ_NO));
user.setUserComment("nothing");
Blob blob=rs.getBlob(BPMConstants.HASH_MAPDATA);
try{
if(blob!=null && !blob.equals("")){
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
ByteArrayInputStream bos = new ByteArrayInputStream(blobAsBytes);
ObjectInputStream out=null;
out = new ObjectInputStream(bos);
HashMap<String, Object> map=null;
map = (HashMap<String, Object>)out.readObject();
user.setMap(map);
}
userList.add(user);
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from blob "+e.getStackTrace());
}
}
return userList;
}
});
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from db "+e.getStackTrace());
}
return users;
}
}
1)
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
The web-inf folder is not (without hacks and problems) accessabel while running the tests.
So the short and easy solution is to put that spring config files in:
(if you use maven): src\main\resources
(if you do not use maven): your java source file root folder
(if you do not use maven but eclipse): create an extra folder (for example resources), put the files in that folder, and then make this folder a eclipse source folder (right click that folder in the package explorer and then choose "Build Path" / "Use as Source Folder")
2)
your BpmProcessorDaoImplTest does not look like a valid test for me.
Either it is a Test case - then its methods have #Test annotations and the class itself have the #ContextConfiguration configuration that points to your configuration file. Or is is a Repository then it has a #Repository annotation and not #Test or #ContextConfiguration. annotations. But I never saw a class that mixed this.
So try this:
#ContextConfiguration("classpath:applicationContext.xml")
#Transactional //make your tests run in an transaction that gets rolled back after the test
public class BpmProcessorDaoImplTest {
/** Class under test */
#Autowired
private BpmProcessorDao dbmProcessorDao;
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
//just to make the example test usefull
#PersistenceContext
private EntityManager em
#Test
public void testWrite() {
DbmProcessor entity = ...;
...
this.dbmProcessorDao.save();
...
em.flush(); //make sure that every is saved before clear
em.clear(); //clear to make read(id) read the entity from the database but not from l1-cache.
int id = entity.getId();
...
DbmProcessor reloadedEntity = this.dbmProcessorDao.read(id);
//getName is just an example
assertEquals(entity.getName(), dbmProcessorDao.getName());
}
}
This will occure when applicationContext.xml cannot be found in class path
Possible solutions :
add directory containing applicationContext.xml to classpath.
give relative path of applicationContext.xml
give absolute path of applicationContext.xml
If 3rd solution worked for you would mean that applicationContext.xml was not in classpath.

declaration can be found for element 'context:property-placeholder'. Spring 4

I browsed around 30 webpages and 50 articles about this and it's still not working.
Here is my code its really simple I'm only a Spring beginner.
App.java
package com.procus.spring.simple.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* #author procus
*/
public class App {
public static void main(String[] args) {
ApplicationContext con = new ClassPathXmlApplicationContext("SpringBeans.xml");
SampleSimpleApplication sam = (SampleSimpleApplication) con.getBean("sam");
sam.run(args);
}
}
SampleSimpleApplication.java
package com.procus.spring.simple.simple;
import com.procus.calculator.basic.BasicCalculator;
import com.procus.spring.simple.simple.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackageClasses = BasicCalculator.class)
public class SampleSimpleApplication implements CommandLineRunner {
// intentional error
#Autowired
BasicCalculator calculator;
// Simple example shows how a command line spring application can execute an
// injected bean service. Also demonstrates how you can use #Value to inject
// command line args ('--name=whatever') or application properties
#Autowired
private HelloWorldService helloWorldService;
public SampleSimpleApplication() {
}
#Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleSimpleApplication.class, args);
}
}
HelloWorldService.java
package com.procus.spring.simple.simple.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
#Component
#Configuration
#PropertySource(value = { "classpath:application.properties" })
public class HelloWorldService {
#Value("${app.name:World}")
private String name;
public String getHelloMessage() {
return "Hello " + this.name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
SpringBeans.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">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:property-placeholder location="classpath*:application.properties"/>
<bean id="DBProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<value>classpath*:application.properties</value>
</property>
</bean>
<bean id="sam" class="com.procus.spring.simple.simple.SampleSimpleApplication"/>
<bean id="serv" class="com.procus.spring.simple.simple.service.HelloWorldService">
<property name="name" value="Jano" />
</bean>
<bean id="calc" class="com.procus.calculator.basic.BasicCalculator">
<constructor-arg value="1.0"/>
</bean>
</beans>
And in resources folder is my application.properties file which contains only app.name=Phil
Exception in thread "main"
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
Line 12 in XML document from class path resource [SpringBeans.xml] is
invalid; nested exception is org.xml.sax.SAXParseException;
lineNumber: 12; columnNumber: 81; cvc-complex-type.2.4.c: The matching
wildcard is strict, but no declaration can be found for element
'context:property-placeholder'.
I really tried most of solutions which I found at stackoverflow and few other forums. I`m really new in spring and I will appreciate any help.
In your springbeans.xml you've specified the location as "classpath*:application.properties" classpath with a * whereas in your HelloWorldService.java you've specified the location as "classpath:application.properties". There is a discrepancy in the two locations.
Besides the problem lies in the SpringBeans.xml schema declaration. It is incorrect & incomplete.
After the context declaration http://www.springframework.org/schema/context/spring-context-4.0.xsd is missing
check this this & this
Ideally it should be
<?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: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">
I am unable to comment -
What i see is you are writing : <context:property-placeholder location="classpath*:application.properties"/>
Why is there a * after classpath.
It should work with - <context:property-placeholder location="classpath:application.properties"/>
Else -
You can use -
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
In you Heloworld bean
<bean id="helloworld" class ="package.HelloWorldService" >
<property name="name" value="${app.name}" />
</bean>

java spring aop: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod

I 've designed a db application, but need to handle the exception connecting to db using spring aop, classes i 've are shown below
LoginInterface.java
LoginInterface(){
ApplicationContext context = new ClassPathXmlApplicationContext("LoginApp.xml");
Login login = (Login) context.getBean("Login");
login.loginMethod(username,password);
}
Login.java
{
loginMethod(String username, char[] pwd) throws ClassNOtFoundException, SQLException{
...
}
}
LoginProfiler.java
package dbapp;
import java.sql.SQLException;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.JoinPoint;
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#Around("loginMethod()")
public void handleException(final ProceedingJoinPoint pJoinPoint )throws Throwable{
try{
pJoinPoint.proceed();
}catch(Exception e) {
if((e.getCause().toString()).contains("UnknownHostException") ){
System.out.println("Unknown Host ");
}else if((e.getCause().toString()).contains("ConnectException")){
System.out.println("Connection Problem ");
}
}
}
}
LoginApp.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: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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-destroy-method="destroy"
default-init-method="afterPropertiesSet"
default-autowire="byName">
<!-- Enable the #AspectJ support -->
<aop:aspectj-autoproxy />
<bean id="LoginProfiler" class="dbapp.LoginProfiler" />
<bean id="Login" class="dbapp.Login" />
</beans>
I've got the following Exception
Erg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Login' defined in class path resource [LoginApp.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at
..
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:315)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:206)
at
Try this.
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#AfterThrowing("loginMethod()")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
or
#Aspect
public class LoginProfiler {
#AfterThrowing("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
Also it would be better if you spend some time learning about spring-aop. From your question it looks like you really don't understand AOP. You are trying to cut and paste from some sample code.

Categories