Scan specific packages for Spring AOP - spring

I'm trying to use AOP into an existing (big) Spring project. The thing is that I don't want Spring to create proxies for all the objects in the ApplicationContext, mainly for performance but also because there are final classes that I cannot modify.
I've tried to make Spring search only inside "com.foo.bar.*" by defining the following aspect:
com.baz.MyAspect
#Aspect
public class MyAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(MyAspect.class);
#Before("within(com.foo.bar.*) && " +
"execution(* com.foo.bar.MyController.handleRequest(..))")
public void getData() {
// Nothing yet
}
}
And I've added this lines to the configuration:
<?xml version="1.0" encoding="utf-8"?>
<beans ...>
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="myAspect" class="com.baz.MyAspect"/>
</beans>
But when I run the app, I get the following Exception:
Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.foobar.FinalController]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class com.foobar.FinalController
So it seems that Spring is scanning packages other than the ones defined in the within expression. I would like to know whether there is a way to specify the packages to be scanned or any other way to solve this problem.

yes you can define your point cut like this
the execution of any method defined in the bar package or a sub-package:
execution(* com.foo.bar...(..)) click here for detail

Related

what is the usage of new keyword while using java configuration in spring

I have a question around the usage of new keyword being used when using java configuration in spring. What is the need of using new keyword
Refer below mentioned example:
Code implemented using Java Config
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
The above code will be equivalent to the following XML configuration
<beans>
<bean id = "helloWorld" class = "com.test.HelloWorld" />
</beans>
In XML config, we do not use new keyword whereas in java config we are using new keyword. can someone please explain the difference
In the XML configuration, you explain to the system what class should be instanciated (there is a "new" but it is behind the scene) but in the Java Config you actually have to return an instance so that is why we use the 'new' keyword. 'new' simply creates an instance of your class.
The two examples shown in question are not really equivalent.
What the
<beans>
<bean id="helloWorld"
class="com.test.HelloWorld" />
</beans>
really does, is it tells Spring to instantiate class com.test.HelloWorld, and name the resulting bean "helloWorld".
Then the java-config approach is not really doing this. Instead this follows the factory-method pattern, when we tell Spring, that the return value of the method is the bean, and the method name is the name of that bean.
An equivalent of that in XML would be the mentioned factory-method approach, which in this case would look something like this:
<beans>
<bean id="helloWorldConfig"
class="com.test.HelloWorldConfig" />
<bean id="helloWorld"
factory-bean="helloWorldConfig"
factory-method="helloWorld" />
</beans>
Note that there are several approaches to factory-method. In the above, we are assuming, the `helloWorldConfig" is the factory, and we're specifying the method on that bean. Theare are cases with static factory methods too. See here for more examples.
<beans>
<bean id = "helloWorld" class = "com.test.HelloWorld" />
</beans>
This XML configurations tells Spring to "create an instance of com.test.HelloWorld and put it in the bean context with bean id helloWorld".
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
In this Java configuration, we are returning an instance of com.test.HelloWorld. Because of the #Bean annotation, this instance is put into the bean context. As no specific bean id is given, the bean id is derived from the method hellowWorld() and thus becomes helloWorld.
As you can see, both configurations require an instance of com.test.HelloWorld. The XML configuration implicitly creates the instance whereas in the Java configuration you have to explicitly do it yourself.

ApplicationContext with same bean having #RequestMapping fails

In my applicationContext.xml I have 2 beans with same class and different id(test and test1). The application context gets loaded correctly, but when I add #RequestMapping to one method then the bean creation fails with the below error. This used to work with AnnotationMethodHandlerAdapter but its failing with RequestMappingHandlerMapping and RequestMappingHandlerAdapter.
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'test1' bean method
public java.lang.String com.test.render()
to {[/render],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'test' bean method
Please suggest how to fix this.
Code:
applicationContext.xml
<bean id="test" class="com.abc.test" />
<bean id="test1" class="com.abc.test" />
Controller
#Controller
#RequestMapping( value ={"/test/", "/test1/"})
public class test {
#RequestMapping("render")
public String render ()
{
//some code here.
}
}
You can do it like this...
switch from singleton approach to prototype and inside the xml do
While programmatically define
class P1 {
#Autowire
NotSoSingleton prototypedBean;
}
class P2 {
#Autowire
NotSoSingleton prototypedBean;
}
class P3 {
#Autowire
NotSoSingleton prototypedBean;
}
Would this approach do?
I could find a work around with this. This solution if for the comments I posted on 21-May
I used order property to instantiate the custom defined RequestMappingHandlerMapping in the xml file and it worked!!
It took my custom defined RequestMappingHandlerMapping instead of the default one loaded by <annotation-driven>.

Spring Lookup Method Injection failing with AbstractMethodError

I have a singleton service class like the below.
#Service
public class SingletonClass{
#Autowired
private ContextProvider provider;
public Context run(){
context = provider.createContext();
updateContext(context)
}
ContextProvider class:
public abstract class ContextProvider implements MyInterface{
public abstract Context createContext();
}
configuration:
<bean name="provider"
class="xyz.s.s.ContextProvider" >
<lookup-method name="createContext"
bean="someBean" />
</bean>
<bean id="somebean" class="com.x.y.someclass" />
<bean id="singletonService" class="com.x.y.SingletonClass" />
When i try to run the above using Junit ->instead of creating the lookup bean on demand, I am getting the below error
org.springframework.beans.factory.BeanCreationException:
aused by: java.lang.AbstractMethodError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1585)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
It seems, the lookup method injection is not working in my case
I found the issue and fixed it.
I was having the abstract class implemented an interface. So at run time,
CGLIB unable to create a proxy class since there are unimplemented methods.
Compiler also did not complain, because this is abstract class and it did not expect us to add all implementations of the interface.
I removed the 'implements ' and it just works fine.
So the contextprovider will become,
public abstract class ContextProvider {
public abstract Context createContext();
}
Posting this message, since people might face same situation.

why there is no corresponding set method in this case?

I am new to Spring and working on a project which is consisting of Spring in it .
It has got this piece of code inside the xml file
<bean id="quotClient" class="com..at.client.QuoteClient" scope="singleton" />
<bean id="streamClient" class="com.at.client.StreamClient" scope="singleton" />
And inside the java class it has got this piece of code
#Autowired
#Qualifier("streamClient")
private StreamClient sclient;
#Autowired
#Qualifier("quotClient")
private QuoteClient quotesClient;
public void setQuotesClient(QuoteClient quotesClient) {
this.quotesClient = quotesClient;
}
Please let me know why there is no method by name set for the StreamClient class , but which has got corresponding set method for QuoteClient .
Since you're using annotation driven Autowiring of the beans you don't need any setters for injunction (these are set by using reflection). Even setQuotesClient isn't needed by Spring DI framework to inject those 2 bean instances.
PS: From spring version 3.0, you can start using #Inject instead of #Autowired.
Check: How does Spring #Autowired work
i think that setter method wrote by mistake.
remove that setter and test the application. it should work.

is there something like #predestroy in the spring as in the castle windsor

Anything like #PreDestroy in the spring-framework?
If you define a bean that implements the DisposableBean interface then Spring will call the
void destroy() throws Exception;
method before destrying the bean.
That's one way, the other is when your bean doesn't have to implement the given interface.
In one of yours ConfigurationSupport classes your bean has to be defined as as pulic method with the #Bean annotation.
#Bean (destroyMethod="yourDestroyMethod")
public YourBean yourBean() {
YourBean yourBean = new YourBean();
return yourBean;
}
The method "yourDestroyMethod" has to be defined in YourBean.class and then Spring will call it before destroying the bean.
For more info see the Spring documentation: Destruction callbacks
UPDATE
The third way... I would even say the better way would be to specifiy "init-method" and "destroy-method" of your bean... like this: mkyong.com/spring/spring-init-method-and-destroy-method-example
This solves the problem ot third-party dependency beans, and liberates the the code unnecessary Spring interfaces..
There are 3 ways to do that.
#PreDestroy tag
destroy-method in xml
DisposableBean interface as stated above
My favorite is the #PreDestroy method.
To do that u need:
In application-context.xml add the following schema:
<?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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="shutDownBean" class="spring.ShutDownBean" />
<context:annotation-config/>
</beans>
The context:annotation-config/ makes the #PreDestroy and the #PostDestroy tags available.
Now lets say that you have the ShutDownBean that you want to run some code when the shutdown callback is called.
The <bean id="shutDownBean" class="spring.ShutDownBean" /> part registers the bean.
import javax.annotation.PreDestroy;
public final class ShutDownBean {
#PreDestroy
public static void shutDownMethod() {
System.out.println("Shutting down!");
}
}
Now you are done.
If you have a desktop application then to use the #PreDestroy annotation you need to close it like this:
AbstractApplicationContext applicationContext =
new ClassPathXmlApplicationContext("application-context.xml");
applicationContext.registerShutdownHook();
note:
AbstractApplicationContext has the implementation of registerShutdownHook() so this is the minimum class you can use.
Also you can use the destroy-method tag for classes you do not control their implementation. For example you can add this in your applcation-context.xml:
<bean id = "dataSource"
class = "org.apache.commons.dbcp.BasicDataSrouce"
destroy-method = "close">
The destroy-method value can have any visibility but needs to have no arguments.
Hope this helps!
You mean like annotating a method with the standard JDK #PreDestroy? That's common enough in Spring, and usually better than using a destroy-method attribute on the bean declaration in XML. All you have to do is include
<context:annotation-config/>
In your configuration file and Spring handles the rest.
there's standard .NET IDisposable.Dispose() method. I don't know Spring but from quick googling it seems that #predestroy is pretty much the same concept.

Resources