I'm playing with the idea of using Spring #Configurable and #Autowire to inject DAOs into domain objects so that they do not need direct knowledge of the persistence layer.
I'm trying to follow http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-atconfigurable, but my code seems to have no effect.
Basically, I have:
#Configurable
public class Artist {
#Autowired
private ArtistDAO artistDao;
public void setArtistDao(ArtistDAO artistDao) {
this.artistDao = artistDao;
}
public void save() {
artistDao.save(this);
}
}
And:
public interface ArtistDAO {
public void save(Artist artist);
}
and
#Component
public class ArtistDAOImpl implements ArtistDAO {
#Override
public void save(Artist artist) {
System.out.println("saving");
}
}
In application-context.xml, I have:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springsource.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
<bean class="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect" factory-method="aspectOf"/>
</beans>
Class path scanning and initialisation is performed by the spring module for Play! framework, although other autowired beans work, so I'm pretty sure this is not the root cause. I'm using Spring 3.0.5.
In other code (inside a method in bean that's injected into my controller using Spring, in fact), I'm doing this:
Artist artist = new Artist();
artist.save();
This gives me a NullPointerException trying to access the artistDao in Artist.save().
Any idea what I'm doing wrong?
Martin
You need to enable load-time weaving (or other kinds of weaving) in order to use #Configurable. Make sure you enabled it correctly, as described in 7.8.4 Load-time weaving with AspectJ in the Spring Framework.
I was having this problem with Tomcat 7 using LTW trying to autowire beans into my domain classes.
There was some updates to the doc for 3.2.x at http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-configurable-container that revealed that one can use #EnableSpringConfigured instead of the xml configuration .
So I have the following annotation on my Domain object:
#Configurable(preConstruction=true,dependencyCheck=true,autowire=Autowire.BY_TYPE)
#EnableSpringConfigured
#EnableSpringConfigured is a substitue for
<context:spring-configured />
and don't forget to add this to your context xml file:
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver" aspectj-weaving="on"/>
Of course I needed to setup Tomcat for load time weaving first.
Also, I ran into a bug in 3.2.0 (null pointer) so I needed to upgrade to Spring 3.2.1 (https://jira.springsource.org/browse/SPR-10108)
All is well now!
You should just look how Spring Roo does it since it does exactly what you want to do.
There are lots of things that can cause the NPE your having but most of the time it has to do with not compiling properly with AspectJ compiler and not having the Spring Aspects jar in your AspectJ lib path (this is different than your classpath).
First just try to get it to work with Maven and the AspectJ compiler plugin. Thats why I recommend Spring Roo as it will generate a POM file with the correct setup.
I have found #Configurable does not really work with LTW (despite one of the answers saying so). You need compile time weaving for #Configurable to work because the advice is happening at object construction time (constructor advice cannot be done with Springs LTW).
First, enable Spring debug logging. I use Log4j to do it. I've created a logger like so (with Log4j xml configuration so I can use RollingFileAppender):
<log4j:configuration>
<appender name="roll" class="org.apache.log4j.rolling.RollingFileAppender">
blah blah configuration blah blah
</appender>
<logger name="org.springframework">
<level value="debug" />
<appender-ref ref="roll" />
</logger>
</log4j:configuration>
This will allow you to see what Spring is doing and when.
Second, you have ArtistDAO autowired but I don't see where you have a bean named ArtistDAO. Your DAO component bean will be named "artistDaoImpl" by default. Try changing #Component to #Component("artistDao") and applying #Autowired to the setter instead:
private ArtistDAO artistDao;
#Autowired
public void setArtistDao(ArtistDAO artistDao)
{
this.artistDao = artistDao;
}
I had the same problem and never managed to get the code working with #Configurable and #Autowired. I finally decided to write an aspect myself which would handle the #Configurable and #Autowired annotations. Here is the code:
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
#SuppressWarnings( "rawtypes" )
#Aspect
public class AutoInjectDependecyAspect implements ApplicationContextAware {
private static final Logger LOGGER = Logger.getLogger( AutoInjectDependecyAspect.class );
private ApplicationContext applicationContext = null;
#Pointcut( "execution( (#org.springframework.beans.factory.annotation.Configurable *).new())" )
public void constructor() {
}
#Before( "constructor()" )
public void injectAutoWiredFields( JoinPoint aPoint ) {
Class theClass = aPoint.getTarget().getClass();
try{
Field[] theFields = theClass.getDeclaredFields();
for ( Field thefield : theFields ) {
for ( Annotation theAnnotation : thefield.getAnnotations() ) {
if ( theAnnotation instanceof Autowired ) {
// found a field annotated with 'AutoWired'
if ( !thefield.isAccessible() ) {
thefield.setAccessible( true );
}
Object theBean = applicationContext.getBean( thefield.getType() );
if ( theBean != null ) {
thefield.set( aPoint.getTarget(), theBean );
}
}
}
}
} catch ( Exception e ) {
LOGGER.error( "An error occured while trying to inject bean on mapper '" + aPoint.getTarget().getClass() + "'", e );
}
}
#Override
public void setApplicationContext( ApplicationContext aApplicationContext ) throws BeansException {
applicationContext = aApplicationContext;
}
}
Next in your spring context define the aspect so that the springcontext will be injected into the aspect
<bean class="[package_name].AutoInjectDependecyAspect" factory-method="aspectOf"/>
Perhaps using the #Repository annotation for the DAO will do it.
try : #Configurable(autowire=Autowire.BY_TYPE). Autowired defaults to off :<
I had a similar issue that I resolved today. The important thing is that you need to enable load-time weaving and make sure the appropriate aspectj classes are loaded. In your pom.xml you need to add the aspectjweaver artifact:
...
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
....
You can change the version if you need to. Then, I would go the xsd route in you application-context.xml instead of the DTD route:
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--Scans the classpath for annotated components #Component, #Repository, #Service, and #Controller -->
<context:component-scan base-package="your.base.package"/>
<!--Activates #Required, #Autowired, #PostConstruct, #PreDestroy and #Resource -->
<context:annotation-config/>
<!--This switches on the load-time weaving for #Configurable annotated classes -->
<context:load-time-weaver/>
</beans>
Also, please verify that your version of AspectJ is current. I wasted a few hours trying to make this work, and the cause was an old version of Aspectjweaver.jar. I updated to 1.7.2 and everything worked like a charm.
There is a bug with #Configurable and LTW. If you use your class as a parameter in any method the auto wiring stops working.
https://jira.spring.io/plugins/servlet/mobile#issue/SPR-8502
Related
I have Spring XML configuration file like this:
<bean id="A" class="a.b.c.d.ConfigurationA" />
<bean class="a.b.c.d.ConfigurationB" />
<bean id="C" class="a.b.c.d.e.ConfigurationC" depends-on="objectFromConfigurationB" />
Each configuration file import other config classes. Example:
#Configuration
#Import({ConfigA.class, ConfigB.class})
class ConfigurationA {
#Bean
public ABC abc() {
return new ABC();
}
...
...
..
}
I would like to rewrite this XML config into Java keeping all relations (depends-on). How can I do it?
I tried with:
ComponentScan
Import
always the same: beans from inner configuration files are not loaded into spring context. I caught No bean 'A' available error during startup.
How to create depends-on relation during import configuration bundle?
With component scanning you should not need to do anything.
#Component
class A {
}
#Component {
class B {
}
#Componet {
class C {
private final B b;
#Autowired
C(B b) {
this.b = b;
}
}
Using constructor injection in component C gets you exactly what you want, there is no need to do the depends on. If you are newer versions of spring you don't even need the #Autowired on the constructor.
I converted a project with about 10 XML spring files into Java Configuration. I found that writing #Bean definitions each one in an #Configuration class was not necessary, I thought it would cause bootup times to be faster but made no difference. Using component scanning is lot less code and makes things much simpler. If you are on spring boot you need to make sure that the packages that have code in them are being scanned, for example if you have library in com.example.lib and the #SpringBootApplication class is in com.example.app then the beans in com.example.lib won't be picked up because by default it will scan only the child packages of com.example.app you will need to add more packages to scan to the config or move the main spring boot app class to com.example
You are looking for #DependsOn in your ConfigurationC as follows: #DependsOn("name-of-bean-B").
I have an aspect which creates by load-time weaving mechanism. But I need to inject my service in it, so it aspect must be created by spring.
My aspect looks like this :
#Aspect
public class SomeAspect {
#Inject
private SomeService someService;
#Before("some_pointcut_here")
public void doInterception() {
//...call service here
}
}
I can do it with xml:
<bean id="myAspect" class="foo.bar.SomeAspect" factory-method="aspectOf" />
So the question is how to achieve the same with spring java config. Any suggestions will be appreciated. Thanks
Edit
I annotate my aspect with #Component and it works. It strange for me because in case of xml config dependency injection doesn't worked in my case, but it works for java configuration
#Bean
public SomeAspect someAspect() {
return org.aspectj.lang.Aspects.aspectOf(SomeAspect.class);
}
I am using spring for quite some time but this morning I came across with some unexpected behavior.
As I could not decide by myself whether that was a desired functionality or a bug I am presenting it here with the hope I will get some good explanations about why would this be happening.
In short I have multiple beans defined in an application context and I create two map beans using utils:map name space with only part of my beans added to those maps. The two maps have exactly the same entries.
Then I auto wire those maps. One auto wire is done using #Autowired annotation and the other one is done using #Resource
To my surprise the bean annotated with #Autowired had got all beans in the context not only the ones I specifically put in the map. The other one auto wired using #Resource annotation had only the expected two entries in it.
I am mainly interested in:
1. Why all the beans declared in my context of that time appear in the #Autowired map and not the ones I added
2. Why #Resource and #Autowired would behave differently
Here is the working code that reproduces the scenario described above.
Some interface here:
package my.testing.pkg;
public interface Foo {
void doStuff();
}
And its implementation:
package my.testing.pkg;
public class FooImpl implements Foo {
#Override
public void doStuff() {}
}
The spring config file:
<?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:utils="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="foo_1" class="my.testing.pkg.FooImpl"/>
<bean id="foo_2" class="my.testing.pkg.FooImpl"/>
<bean id="foo_3" class="my.testing.pkg.FooImpl"/>
<bean id="foo_4" class="my.testing.pkg.FooImpl"/>
<utils:map id="fooMap1" map-class="java.util.HashMap">
<entry key="foo_1" value-ref="foo_1"/>
<entry key="foo_2" value-ref="foo_2"/>
</utils:map>
<utils:map id="fooMap2" map-class="java.util.HashMap">
<entry key="foo_1" value-ref="foo_1"/>
<entry key="foo_2" value-ref="foo_2"/>
</utils:map>
</beans>
And the test case to reproduce the behavior:
package my.testing.pkg;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.Map;
import static org.junit.Assert.assertEquals;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "/test-context.xml")
public class SpringMapCreatingTest {
#Autowired
private Map<String, Foo> fooMap1;
#Resource
private Map<String, Foo> fooMap2;
#Test
public void shouldInjectATwoEntriesMap() throws Exception {
assertEquals("fooMap1 should have to entries", 2, fooMap1.size());
assertEquals("fooMap2 map should have to entries", 2, fooMap1.size());
}
}
Thank you in advance for your clarifications.
What is happening there is the following:
The #Autowired dependency will look for beans that match its type, and in this case it will create a map of your beans Foo mapped by their name. The same behavior will happen when you autowire on a list of beans, Spring will inject all the beans that implement the interface.
The #Resource dependency will look first for a bean that matches the dependency name, e.g fooMap2 and will inject it.
Take a look at the documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers
Maps / List are not handled as "standard" beans injection.
Take a look to those questions on so: Can spring #Autowired Map?
https://stackoverflow.com/a/13914052/1517816
HIH
Check the spring docs, the tips section:
beans that are themselves defined as a collection or map type cannot
be injected through #Autowired, because type matching is not properly
applicable to them. Use #Resource for such beans
So it is better to use #Resource and not #Autowired for maps
I'm using Spring and am trying to autowire (using annotations) a DAO into a Service, which is then wired into a controller. Having
#Autowired
Movie movieDao;
on its own doesn't work, as I think the new method gets called, so that DAO isn't managed by Spring. The following does work, but it will look messy if I have to copy and paste that context configuration into each method
#Autowired
MovieDao movieDao;
#Override
public List<Movie> findAll() {
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load("classpath:app-context.xml");
context.refresh();
MovieDao movieDao = (MovieDao) context.getBean("movieDao", MovieDao.class);
return movieDao.findAll();
}
where this code is in my Service class. Is there a more elegant way to ensure that my DAO is initialised properly, rather than copying and pasting the first 4 lines of that method into each Service method?
[edit] The class that contains the code above is a class called MovieServiceImpl, and it essentially corresponds to the DataServicesImpl class in the architecture described on this page. (I'll add a summary/description of that architecture and what I'm trying to do soon). This is the code: http://pastebin.com/EiTC3bkj
I think that the main problem is that you want to instantiate your service directly (with new) and not with Spring:
MovieService movieService = new MovieServiceImpl();
When you do this, your MovieServiceImpl instance is constructed but not initialised (the field #Autowired MovieDao is null).
If you want to instantiate properly your object with field injection, you need to use Spring. As explained in the documentation or in this example, you can automatically detect all your annotated beans and initialize them in your context with the component scanning.
Example
In your case, using annotiations on (#Component, #Service, etc) and in (#Autowired, #Inject, etc) your beans, your project could look like this:
Spring configuration app-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Use component scanning to auto-discover your beans (by annotation) and initialize them -->
<context:component-scan base-package="com.se325.a01" />
<!-- No need to declare manually your beans, because beans are auto-discovered thanks to <context:component-scan/> -->
</beans>
Entry point of your application App.java
package com.se325.a01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.se325.a01.model.Movie;
import com.se325.a01.service.MovieService;
public class App {
public static void main(String[] args) {
// Let's create the Spring context based on your app-context.xml
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"app-context.xml"});
// Now your context is ready. All beans are initialised.
// You can retrieve and use your MovieService
MovieService movieService = context.getBean("movieService");
Movie matrixMovie = new Movie("Matrix");
movieService.create(matrixMovie);
}
}
In fact, when you are using Spring, it is really important to understand how the context is initialized. In the example above, it can be sum up as:
Your entry point App#main is called.
The configuration app-context.xml is loaded by ClassPathXmlApplicationContext.
The package com.se325.a01 is scanned thanks to the line <context:component-scan base-package="com.se325.a01" />. All annotated beans (#Component, #Service, etc) are contructed but not yet initialised.
When all the beans are constructed, Spring initialises them by injecting dependencies. In the example, the #Autowired annotations which mark the dependencies are also discovered thanks to the line <context:component-scan ... \>.
The context is ready with all beans :)
Notes
All this answer explains how you can use component scanning and annotations to use Spring in a main entry point. However, if you are developing a server application, the entry point is the WEB-INF/web.xml.
As #chrylis said, field injection is error prone. Prefer using constructor-based injection.
Before certain methods (or as of now all the methods) I have to call the method of an Aspect to log some messages. My application is functioning correctly otherwise but none of the methods of the Aspect class are called.
I have tried the same cutpoint in same folder structure in my local application but when I try to include it with ZK i am having issues. I have also modified my application-context.xml to support AOP.
This is my aspect class :
package com.mypckg.services.impl;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class MyIntercpeter {
#Pointcut("execution(* com.mypckg.services.impl.MyService.getStudents(..))")
public void performance() {
}
#Before("performance()")
public void doSomethingBeforeExecution() {
System.out.println("Before execution method called...");
}
#AfterReturning("performance()")
public void doSomethingAfterExecution() {
System.out.println("After execution method called...");
}
}
The modifications I made in the application-context.xml are
<beans .........
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
..........
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
.....
<aop:aspectj-autoproxy />
<context:annotation-config />
Am I missing something? Thanks in advance.
Looks like you missed an obvious thing : you forgot to declare beans in spring config?
From Spring docs:
Spring AOP only supports method execution join points for Spring beans, so you can think of a pointcut as matching the execution of methods on Spring beans.
http://static.springsource.org/spring/docs/2.0.x/reference/aop.html
You can declare your beans with annotations or by config.
Also would be better to put a version of spring you use (I supposed it was 2.0.x).