Yes. It is not being set by DI of Spring as the instance you created using new keyword is not being managed by Spring container. Spring will by default inject dependencies only for spring managed instances. So to resolve this problem you can do it by two ways. First is don't use the new
and use @Autowired
on Mybean
instance.
Second is to use @Configurable
on MyBean
class. With the @Configurable
annotation spring will inject dependencies even for objects created through new
keyword. Remember to have AspectJ
jars on your classpath with @configurable
annotation as Spring need them to inject Dependecies.
For the second approach use @Configurable(preConstruction = true)
and add the following dependencies to your pom.xml
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>3.1.1.RELEASE</version>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.8</version>
</dependency>
You also need to compile it through AspectJ Compiler so that Byte code generated has the required abilities. You should use the following entries to make sure system using AspectJ Compiler at compile time.
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.4</version>
<configuration>
<showWeaveInfo>true</showWeaveInfo>
<source>1.6</source>
<target>1.6</target>
<Xlint>ignore</Xlint>
<complianceLevel>1.6</complianceLevel>
<encoding>UTF-8</encoding>
<verbose>false</verbose>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.11</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>