nullpointer exception in aspectJ example - java

I am trying to implement one of the suggestion given by our stackoverflow member here Logging entry, exit and exceptions for methods in java using aspects . Since this is different question in itself, posting here again.
I have tried to search but looks like different versions have different ways of doing it and unable to figure out an example online. I have tried the following simple example since I am new to aspect oriented programming and couldn't figure out how to implement. This example is throwing NPE. Please help me understand where I am doing it wrong.
==== Exception
Exception in thread "main" java.lang.NullPointerException
at aoplogging.SimpleCall.call(SimpleCall.java:13)
at aoplogging.App.main(App.java:18)
Exactly at SimpleService.simpleCall();
ApplicationContext:
<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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.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/jee http://www.springframework.org/schema/jee/spring-jee-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/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<aop:aspectj-autoproxy />
<bean id="simpleCall" class="aoplogging.SimpleCall" />
==================
App.java
package aoplogging;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
SimpleCall call =(SimpleCall) context.getBean("simpleCall");
call.call();
context.close();
}
============ SimpleCall.java
package aoplogging;
import org.springframework.beans.factory.annotation.Autowired;
public class SimpleCall {
#Autowired
private SimpleService SimpleService;
public void call(){
SimpleService.simpleCall();
try {
SimpleService.processingOperator();
} catch (SMSProcessingException | SMSSystemException e) {
e.printStackTrace();
}
}
}
=====Logging.java
package aoplogging;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class Logging {
#Pointcut("execution(* aoplogging.*.*(..))")
private void selectAll(){}
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
#Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
/**
* This is the method which I would like to execute
* after a selected method execution.
*/
#After("selectAll()")
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}
/**
* This is the method which I would like to execute
* when any method returns.
*/
#AfterReturning(pointcut = "selectAll()", returning="retVal")
public void afterReturningAdvice(Object retVal){
System.out.println("Returning:" + retVal.toString() );
}
/**
* This is the method which I would like to execute
* if there is an exception raised by any method.
*/
#AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception: " + ex.toString());
}
}

I am supporting my suggestion ;).
The usage of Spring AOP/AspectJ is problematic when using beans that are not injected by using interface (using the interface ate the injection point), as the interfaces are proxied by AspectJ.
There is a way to come around this by adding proxy-target-class="true" to
<aop:aspectj-autoproxy />
but that is not a nice way.
It is much more simpler and safer to use interfaces.
EDIT: Another error is that you are missing a bean that is implementing SimpleService. It would be easier to add
<context:component-scan base-package="aoplogging" />
to your applicationContext.xml.
Then, you have to tag all beans with
#Component
in order to let Spring know that they are beans that Spring should instantiate.
EDIT: The aspect has to be annotated with both #Aspect and #Component in order to let Spring detect it.

Related

Springcache not working only with XML configuration

I am implementing Springcache with XML configuration and want to get rid of all the annotations. I just want to replace the annotations in the applicationContext.xml file. Here is my code -
//DummyBean.java
package com.spring.example;
interface DummyBean {
public String getCity();
}
//DummyBeanImpl.java
package com.spring.example;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
#EnableCaching
#CacheConfig(cacheNames={"myCache"})
public class DummyBeanImpl implements DummyBean {
private String city = "New York";
#Cacheable()
public String getCity() {
System.out.println("DummyBean.getCity() called!");
return city;
}
}
SpringAwareAnnotationXMLConfig.java
package com.spring.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class SpringAwareAnnotationXMLConfig {
public static void main(String[] args) throws Exception {
AbstractApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml");
DummyBean personService = (DummyBean) context.getBean("myBean");
System.out.println(personService.getCity());
System.out.println(personService.getCity());
System.out.println(personService.getCity());
((AbstractApplicationContext) context).close();
}
}
applicationContext.xml
<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:cache="http://www.springframework.org/schema/cache"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd>
<context:annotation-config/>
<cache:annotation-driven cache-manager="cacheManager"/>
<context:component-scan base-package="com.spring"/>
<bean id="myBean" class="com.spring.example.DummyBeanImpl"/>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="myCache"/>
</set>
</property>
</bean>
<cache:advice id="cacheAdvice" cache-manager="cacheManager">
<cache:caching cache="myCache">
<cache:cacheable method="getCity"/>
</cache:caching>
</cache:advice>
</beans>
As you can see if I keep the #EnableCaching, #CacheConfig, #Cacheable annotations in the Java code, then caching is working fine and I am getting the following output -
DummyBean.getCity() called!
New York
New York
New York
But if I remove the annotations, then I am getting the following output -
DummyBean.getCity() called!
New York
DummyBean.getCity() called!
New York
DummyBean.getCity() called!
New York
This means that the caching didn't work!
But my expectation is that in the applicationContext.xml file I have already enabled the cache by <cache:annotation-driven cache-manager="cacheManager"/>, I have already mentioned the cachename and I have already configured the cache with the method names where caching is to be implemented. So if I omit the annotations, I should get the desired output. But why I am not getting?
Thanks
Nirmalya
When using XML configured aspects you will also need to add an aop:config section to have the aspect applied.
<aop:config>
<aop:advisor advice-ref="cacheAdvice" pointcut="execution(* com.spring.example.DummyBean+.*(..))"/>
</aop:config>
Assuming DummyBean is an interface implemented by com.spring.example.DummyBeanImpl this should do the trick. This states that you want to apply the cacheAdvice (the aspect) to the bean matching the expression.
See also the reference guide

Why is my AOP aspect returning null?

This Before execution code is not working? It is returning null because datap is not set from my_int_it_method() method. #Before should have executed my_int_it_method() then only send() would work.
Aspect AOP code here:
package org.main;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class data {
Connection con = new db_connect().connect();
String datap;
String test;
#Before("execution(public String send())")
public void my_int_it_method() {
String query = "Select * from shapes where shape_id=?";
PreparedStatement pstmt;
try {
pstmt = con.prepareStatement(query);
pstmt.setInt(1, 2);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
datap=rs.getString("type");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public String send() {
return datap;
}
}
XML configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<aop:aspectj-autoproxy/>
<bean name = "data" class="org.main.data" autowire="byName"/>
</beans>
Execution code here:
package org.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");
data dataa = ctx.getBean("data",data.class);
dataa.send();
}
}
The problem is that you are defining your aspect and target (send method) in the same class.
From the AOP Spring documentation
In Spring AOP, it is not possible to have aspects themselves be the target of advice from other aspects. The #Aspect annotation on a class marks it as an aspect and hence excludes it from auto-proxying.
In other words, the moment a class is annotated with a #Aspect it cannot be proxied, which is needed for AOP to work.
The solution for this is to extract your aspect to a new class. This, however, will cause you some other problems since you will not have access to the datap you wanted to set.
I have to be honest I am not sure that your current example is best solved with AOP.
If you wish to read more on AOP have look at the AOP Spring Documentation. It is quite clear with loads of examples.

No bean named is defined Exception

package com.mkyong.output;
IOutputGenerator.java
public interface IOutputGenerator
{
public void generateOutput();
}
package com.mkyong.output;
OutputHelper.java
#Component
public class OutputHelper {
#Autowired
IOutputGenerator outputGenerator;
public void generateOutput() {
outputGenerator.generateOutput();
}
/*//DI via setter method
public void setOutputGenerator(IOutputGenerator outputGenerator) {
this.outputGenerator = outputGenerator;
}*/
}
package com.mkyong.output.impl;
CsvOutputGenerator.java
#Component
public class CsvOutputGenerator implements IOutputGenerator {
public void generateOutput() {
System.out.println("This is Csv Output Generator");
}
}
SpringBeans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.mkyong" />
</beans>
i am getting this exception Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'OutputHelper' is defined
even though i have marked OutputHelper as component.
I have changed
OutputHelper output = (OutputHelper) context.getBean("OutputHelper");
to
OutputHelper output = (OutputHelper) context.getBean("outputHelper");
and it worked.
Hi i think you haven't added following in your Spring XML configuration
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<mvc:annotation-driven/>
you need to see top exception and read the whole line.
i guess there have a exception is nested exception just like #Autowired xxxxxx,meas autowired fail.
i have notice this:
#Autowired
IOutputGenerator outputGenerator;
and
#Component
public class CsvOutputGenerator implements IOutputGenerator
so, in the default, class name is used to #Autowired,you can rewrite to
#Autowired
IOutputGenerator csvOutputGenerator;
notice:
"csvOutputGenerator" first letter is lowercase
the easier option would be to enable annotations in beans already registered in the application context, means that you can just use #Autowired instead of getting manually all beans with context.getBean()
just add this line to your SpringBeans.xml
<context:annotation-config>
if you really want to understand what you are doing reading this could help.

Spring #AspectJ: Advice not applied

I'm trying to weave in code before the call of start();
This is the TestClass I want to advice:
package com.test;
public class TestClass {
public static void main(String[] args) {
new TestClass().start();
}
private void start() {
System.out.println("Test started");
}
}
This is the aspect including the advice:
package com.test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class LogAspect {
#Before("call(void com.test.TestClass.start())")
public void logBefore(JoinPoint joinPoint) {
System.out.println("logBefore() is running");
}
}
This is my spring.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy/>
<context:annotation-config/>
<context:component-scan base-package="com.test"/>
I have also tried to name the beans explicitly in the XML like this:
<aop:aspectj-autoproxy/>
<bean id="test" class="com.test.TestClass" />
<bean id="aspect" class="com.test.LogAspect" />
This is my project setup (I'm using the Spring Tool Suite version 3.1.0):
The result is that TestClass.start is called just fine, but the advice is not applied.
What do I have to change so the advice is applied?
Thanks.
Edit: I finally got it to work:
After editing my code according to your suggestions I had a look at this tutorial. This led me to let my TestClass implement an interface. And that fixed the problem.
Here is my final setup:
The TestClass including its interface:
package com.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
interface TestClass {
void start();
}
public class TestClassImpl implements TestClass {
public static void main(String[] args) {
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
"Spring-Config.xml");
TestClass t1 = (TestClass) appContext.getBean("myTest");
t1.start();
}
#Override
public void start() {
System.out.println("test");
}
}
The aspect:
package com.test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
#Aspect
public class LogAspect {
#Before("execution(void com.test.TestClass.start(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("logging before "
+ joinPoint.getSignature().getName());
}
}
And the Spring-Config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy/>
<bean id="myTest" class="com.test.TestClassImpl" />
<bean id="logAspect" class="com.test.LogAspect" />
</beans>
Thanks for your help.
A call AspectJ pointcut applys when the method is called from another class. As you're calling this directly yourself you should use an execution pointcut, so change:
#Before("call(void com.test.TestClass.start())")
to
#Before("execution(void com.test.TestClass.start())")
Also let the Spring create the bean instead of creating one directly yourself.
Aside: Note, you can keep your Spring XML files separate from your source files in src/resources and they will be picked up by ClassPathXmlApplicationContext.

Spring AOP #Pointcut not triggering

I want to trigger a method when a particular method from another class is invoked that is why I thought of using #Pointcut.
The code below is almost identical to the that I am coding and I don't what else I have to add.
public class OrgManagerImpl implements OrgManager {
public IOrg getOrg(String orgShortName) {
}
}
and this is the class that will should be triggered:
#Aspect
public class OrgManagerSynchronizer {
#Pointcut("execution(* com.alvin.OrgManager.getOrg(..))")
public void classMethods() {}
#Before("classMethods()")
public void synchronize(JoinPoint jp) {
//code should be executed. but does not execute.
}
}
and in my .xml this was specified:
aop:aspectj-autoproxy
What more should I add? What to do next?
Check below things.
1) Check if OrgManagerImpl is either defind as bean in context xml or it is marked as #Component & in context xml you have or that classes's package.
2) If above thing is correct then try changing pointcut as below
#Pointcut("execution(* get*(..))")
This pointcut intercepts all get methods. See if with this point cut your synchronize method is working or not. If it works then at least your spring configurations are fine. you just need to refine pointcut expression. But if this also doesn't work then there is something wrong with your spring aop configuration itself, so we can concentrate on those.
Also if this doesn't work then try to give some more info like you context xml, bean java classes etc.
Two things you need to check.
aop:aspectj-autoproxy is enabled in configuration
The Point Cut / Aspect / Target are spring bean
The below is my xml config example.
<?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:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.techoffice"/>
<bean class="com.techoffice.example.ExampleAspect"/>
</beans>
ExampleAspect.java
package com.techoffice.example;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class ExampleAspect {
#Pointcut("execution (* com.techoffice..*(..))")
public void anyRun() {}
#Before(value="anyRun()")
public void beforeAnyRun(JoinPoint jointPoint){
System.out.println("Before " + jointPoint.getClass().getName() + "." + jointPoint.getSignature().getName());
}
#After(value="anyRun()")
public void afterAnyRun(JoinPoint jointPoint){
System.out.println("After " + jointPoint.getClass().getName() + "." + jointPoint.getSignature().getName());
}
}
HelloWorldExample
package com.techoffice.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class HelloWorldExample {
public void run(){
System.out.println("run");
}
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorldExample helloWorldExample = context.getBean(HelloWorldExample.class);
helloWorldExample.run();
}
}

Categories