JSF and Spring AOP #Around not beeing invoked - java

Hello I'm newbie in Spring AOP.
I have writed something like this:
My Annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface ExceptionHandling {
String onSuccess();
String onFailture();
}
Aspect Class:
#Aspect
public class ExceptionHandler implements Serializable {
#Pointcut(value="execution(public * *(..))")
public void anyPublicMethod() {
}
#Around("anyPublicMethod() && #annotation(exceptionHandling)")
public Object displayMessage(ProceedingJoinPoint joinPoint,ExceptionHandling exceptionHandling) throws FileNotFoundException {
try{
Object point = joinPoint.proceed();
new PrintWriter(new File("D:\\log.txt")).append("FUUCK").flush();
FacesMessageProvider.showInfoMessage(
FacesContext.getCurrentInstance(),exceptionHandling.onSuccess());
return point;
} catch(Throwable t) {
new PrintWriter(new File("D:\\log.txt")).append("FUUCK").flush();
FacesMessageProvider.showFatalMessage(
FacesContext.getCurrentInstance(),
exceptionHandling.onFailture());
return null;
}
}
}
Method from ManagedBean
#ExceptionHandling(onSuccess=IMessages.USER_UPDATED,onFailture=IMessages.WRONG_DATA)
public void onClickUpdateFromSession(){
onClickUpdate(sessionManager.getAuthenticatedUserBean());
}
And app-config.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
">
<aop:aspectj-autoproxy/>
<bean id="exceptionHandler"
class="eteacher.modules.ExceptionHandler"/>
<bean id="sessionManager"
class="eteacher.modules.SessionManager"
scope="session"/>
</beans
I'm trying to make exception handler using Spring AOP
and JSF messages but it does not fire the advice.
Please help me.

Spring AOP will only work on Spring managed beans i.e. beans in the ApplicationContext. As your JSF beans aren't managed by Spring but by the JSF container the AOP part isn't going to work.
To make it work either make your JSF managed beans Spring managed beans (see the Spring Reference Documentation for that) or switch to loadtime or compile time weaving of your Aspects.
A note on loadtime weaving is that it might nog work if your JSF classes get loaded before the Spring context is loaded, the newly registered custom classloader cannot modify the bytecode of already loaded classes.

Related

Spring aop breaks original code? The field of the autowired bean becomes null when the aspect is enabled

When the aspect is enabled, the #Autowired bean in BeanB becomes a proxy, and the name field is null. Why? What should I do if I wish the original code to work properly?
Here is the code:
public class BeanA
{
#Value("jami")
//public String name;
String name; //package visiblity
}
public class BeanB
{
#Autowired
private BeanA beanA;
public void noLongerWorks()
{
System.out.println(beanA.name);
}
}
public class Main
{
public static void main(String[] args)
{
String[] configs = {"applicationContext.xml", "applicationContext-aop.xml"};//prints null
// String[] configs = {"applicationContext.xml"};//prints jami
ApplicationContext ctx = new ClassPathXmlApplicationContext(configs);
BeanB beanB = ctx.getBean(BeanB.class);
beanB.noLongerWorks();
}
}
---------- 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:context="http://www.springframework.org/schema/context"
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">
<context:annotation-config />
<bean class="aop.pack1.BeanA" />
<bean class="aop.pack1.BeanB" />
</beans>
------ applicationContext-aop.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy />
<bean class="aop.pack1.TestAspect" />
</beans>
#Aspect
public class TestAspect
{
#Pointcut("target(aop.pack1.BeanA)")
public void pointcut() {}
#Before("pointcut()")
public void advice()
{
System.err.println("___________advice__________");
}
}
EDIT:
I figured out one possible solution. But it does not seems very clean. Is there any elegant way to this? without making changes to existing code?
The solution I found:
is to make all the fields in BeanA private, and only access them via getter setters.
This approach, however, requires a lot of modification of the original code (e.g. the BeanA class).
You have already figured out the issue but, I wanted to share this article I came across that lists what Spring AOP can and cannot do.
In your case
Since it uses proxy-based AOP, only method-level advising is supported; it does not support field-level interception So join-points can be at method level not at field level in a class.
Only methods with public visibility will be advised: Methods with private, protected, or default visibility will not be advised.
Just a recommendation and I think it's also a good OOP practice to create fields with private or protected visibility and provide appropriate getters and setters to access them.
These SO Q/A might be useful
Spring AOP - get old field value before calling the setter
spring singleton bean fields are not populated
Spring AOP CGLIB proxy's field is null

Aspects are not executed

I'm trying to test a simple Aspect.
The app compiles and runs fine, BUT I do not get the Aspect executed. Or at least, I do not get the output the aspect should produce.
(my aim is to write an exception logger for any ex that occures in the app. but first this test aspect should run...)
Maybe someone who has more experience in aspects see's what I'm doing wrong?
package business;
public interface Customer {
void addCustomer();
}
import org.springframework.stereotype.Component;
#Component
public class CustomerImpl implements Customer {
public void addCustomer() {
System.out.println("addCustomer() is running ");
}
}
#RequestScoped #Named
//this is backing bean for jsf page
public class Service {
#Inject
Customer cust;
add() {
System.out.println("Service is running ");
cust.addCustomer();
}
}
#Aspect
public class AspectComp {
#Before("within(business..*)")
public void out() {
System.out.println("system out works!!");
}
}
Spring:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
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
">
<context:annotation-config />
<context:component-scan base-package="business" />
<aop:aspectj-autoproxy />
</beans>
Output:
Service is running
addCustomer() is running
The Aspect statement is missing.
You are creating your Component with its constructor, and not getting it from Spring container! That's the problem, or you must use AspectJ's load-time weaver.
Just inject your component (CustomerImpl) in your service and then use the injected instance.
I remember having a similar problem once; Spring wasn't actually loading the proxy as it did not recognize the #Aspect annotation as being an annotation-scanable bean. I added the #Component annotation to the #Aspect notation and Spring started scanning it.
I never looked into the reasons why this happened, and why I needed to do that, so I cannot confirm that is the "proper" way of doing things. My gut would tell me that I had something missing in my config file; I can't imagine why Spring would not scan for #Aspect beans.
The other thing you can do, is to explicitly declare your Aspect bean in the XML config file as well to see if this the same type of problem you're having.
You can also enable debug logging in the Spring framework and see if your bean is being loaded by Spring. If not, then it gives you an idea where to start looking.

Spring AOP Configuration for Intercepting All Exceptions

I am struggling to write/configure a ThrowsAdvice interceptor that I want to intercept all exceptions thrown throughout my project:
public class ExceptionsInterceptor implements ThrowsAdvice
{
public void afterThrowing(final Method p_oMethod, final Object[] p_oArgArray,
final Object p_oTarget, final Exception p_oException)
{
System.out.println("Exception caught by Spring AOP!");
}
}
I have already successfully configured a MethodInterceptor implementation that intercepts particular methods that I want to profile (see how long it takes them to execute). Here is the XML config file I have so far:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"/>
<bean name="profilingInterceptor" class="org.me.myproject.aop.ProfilingInterceptor"/>
<bean name="exceptionsInterceptor" class="org.me.myproject.aop.ExceptionsInterceptor"/>
<aop:config>
<aop:advisor advice-ref="profilingInterceptor" pointcut="execution(* org.me.myproject.core.Main.doSomething(..))"/>
</aop:config>
My ProfilingInterceptor works perfectly and intercepts precisely when my Main::doSomething() method gets invoked - so I known I'm ontrack. Using XmlSpy to look at Spring AOP's schema, it looks like I can add something like the following in order to get my ExceptionsInterceptor to intercept all thrown exceptions:
<aop:aspect>
<after-throwing method=""/>
</aop:aspect>
However I cannot find any documentation where this is used as an example, and I have no idea how to configure the method attribute so that its a "wildcard" (*) and matches all classes and all methods.
Can anyone point me in the right direction? Thanks in advance!
According to aspectJ examples method parameter refers to #AfterThrowing advice method:
#Aspect
public class LoggingAspect {
#AfterThrowing(
pointcut = "execution(* package.addCustomerThrowException(..))",
throwing= "error")
public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
//...
}
}
and then the configuration:
<aop:after-throwing method="logAfterThrowing" throwing="error" />
Hope it helps.

How to add Spring Beans automatically to a TaskExecutor

I'm looking for a way to have spring beans registering themselves to a job processor bean who in turn will execute the registered beans on a schedule.
I'm hoping that the bean would just have to implement an interface and by some spring mechanism get registered to the job processor bean. Or alternatively inject the job processor bean into the beans and then somehow the job processor bean can keep track of where it's been injected.
Any suggestions appreciated, it might be that spring is not the tool for this sort of thing?
Use a spring context something 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"
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">
<!--Scans the classpath for annotated
components #Component, #Repository,
#Service, and #Controller -->
<context:component-scan base-package="org.foo.bar"/>
<!--Activates #Required, #Autowired,
#PostConstruct, #PreDestroy
and #Resource-->
<context:annotation-config/>
</beans>
And define a pojo like this:
#Component
public class FooBar {}
And inject like this:
#Component
public class Baz {
#Autowired private FooBar fooBar;
}
Spring has a powerful abstraction layer for Task Execution and Scheduling.
In Spring 3, there are also some annotations that you can use to mark bean methods as scheduled (see Annotation Support for Scheduling and Asynchronous Execution)
You can let a method execute in a fixed interval:
#Scheduled(fixedRate=5000)
public void doSomething() {
// something that should execute periodically
}
Or you can add a CRON-style expression:
#Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}
Here's the XML code you'll need to add (or something similar):
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>
Used together with
<context:component-scan base-package="org.foo.bar"/>
<context:annotation-config/>
as described by PaulMcKenzie, that should get you where you want to go.

Spring #Required annotation not working as expected

I'm trying to test out Spring Annotations to see how they work with some simple examples derived from the Spring 3.0 Source (in this case the "#Required" annotation specifically).
To start, I came up with a basic "Hello World" type example that doesn't use any annotations. This works as expected (i.e. prints "Hello Spring 3.0~!").
I then added a DAO object field to the Spring3HelloWorld class. My intention was to deliberately cause an exception to occur by annotating the setter for the DAO with #Required but then not setting it. However, I get a null pointer exception (since this.dao is null) when I was expecting an exception based on not following the annotation "rules/requirements".
I thought I would have needed to set the DAO object before calling any method from Spring3HelloWorld, but apparently that's not the case. I assume I'm misunderstanding how #Required works.
So basically how would I get the following to give me an error along the lines of "Hey you can't do that, you forgot to set DAO blah blah blah".
Spring3HelloWorldTest.java:
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Spring3HelloWorldTest {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource ("SpringHelloWorld.xml"));
Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory.getBean("spring3HelloWorldBean");
myBean.sayHello();
}
}
Spring3HelloWorld.java:
import org.springframework.beans.factory.annotation.Required;
public class Spring3HelloWorld {
private DAO dao;
#Required
public void setDAO( DAO dao ){
this.dao = dao;
}
public void sayHello(){
System.out.println( "Hello Spring 3.0~!" );
//public field just for testing
this.dao.word = "BANANA!!!";
}
}
SpringHelloWorld.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<bean id="dao" class="src.DAO" ></bean>
<bean id="spring3HelloWorldBean" class="src.Spring3HelloWorld" ></bean>
</beans>
My first guess is you won't get any of the advanced behaviour with Spring and annotations because you are using an XmlBeanFactory instead of the recommended ApplicationContext.
-- edit --
Yup - see this Stack Overflow question/answer.

Categories

Resources