Autowiring does not work in Spring 3.1.2, JUnit 4.10.0

Using Spring 3.1.2, JUnit 4.10.0 and quite new for both versions. I'm having a problem in that I cannot get annotation-based autoinstallation to work.

Below are two samples, one of which does not use annotations, which works fine. And the second is an annotation that does not work, and I cannot find a reason. I pretty often followed spring -mvc-test samples.

IN

package com.company.web.api; // imports public class ApiTests { @Test public void testApiGetUserById() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("/com/company/web/api/ApiTests-context.xml"); UserManagementService userManagementService = (UserManagementService) ctx.getBean("userManagementService"); ApiUserManagementController apiUserManagementController = new ApiUserManagementController(userManagementService); MockMvc mockMvc = standaloneSetup(apiUserManagementController).build(); // The actual test mockMvc.perform(get("/api/user/0").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } } 

Failure , because userManagementService is null, not auto-validating:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration // should default to ApiTests-context.xml in same package public class ApiTests { @Autowired UserManagementService userManagementService; private MockMvc mockMvc; @Before public void setup(){ // SetUp never gets called?! } @Test public void testGetUserById() throws Exception { // !!! at this point, userManagementService is still null - why? !!! ApiUserManagementController apiUserManagementController = new ApiUserManagementController(userManagementService); mockMvc = standaloneSetup(apiUserManagementController).build(); // The actual test mockMvc.perform(get("/api/user/0").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } } 

Note that both of the above test classes must use the same context configuration, and userManagementService is defined here.

ApiTests-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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" 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/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8"/> <property name="username" value="user"/> <property name="password" value="passwd"/> </bean> <!-- Hibernate SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingResources="company.hbm.xml"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> </props> </property> <property name="eventListeners"> <map> <entry key="merge"> <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/> </entry> </map> </property> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/> <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= --> <context:annotation-config/> <tx:annotation-driven/> <context:mbean-export/> <!-- tried both this and context:component-scan --> <!--<bean id="userManagementService" class="com.company.web.hibernate.UserManagementServiceImpl"/>--> <context:component-scan base-package="com.company"/> <!-- Hibernate JMX statistics service --> <bean name="application:type=HibernateStatistics" class="org.hibernate.jmx.StatisticsService" autowire="byName"/> </beans> 

and the UserManagementService interface (interface), as well as UserManagementServiceImpl, has the @Service annotation.

Two minor questions / observations: setup () is never called, although it does have an @Before annotation. In addition, I noticed that my test methods are not executed / are not recognized if they do not start with the name "test", which is not the case, although with all the spring -mvc-test samples that I saw.

pom.xml:

  <dependency> <groupId>org.junit</groupId> <artifactId>com.springsource.org.junit</artifactId> <version>4.10.0</version> <scope>test</scope> </dependency> 

enter image description here

Update:

The problem only occurs when running tests with maven; this is normal when I run a test from my IDE (IntelliJ IDEA).

  <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.3</version> <configuration> <includes> <include>**/*Tests.java</include> </includes> </configuration> </plugin> 
+8
spring spring-annotations spring-test-mvc junit junit4
source share
3 answers

Auto-messaging will not happen unless you scan components.

Why did you comment on this in your code?

 <!--<context:component-scan base-package="com.company"/>--> 

Also re: junit. If you are in eclipse, you can just go to the pom dependency tree and filter junit. Make sure that you are actually using this version and not pull the older junit.

Edit: Well, I just checked your configuration and was able to get it to work on this side. My only assumption is that you somehow run it with a bad test runner that forces it to use the wrong unit.

Change 2 (SOLVED) . Thus, it turns out that the problem is that you are using a custom version of junit. Surefire is looking for the provided junit library and cannot find it. As a result, junit 3 is used by default, which is why your application skips loading the configuration.

You can specify a specific provider, for example

 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.3</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.12.3</version> </dependency> </dependencies> </plugin> 

But I found that it does not work with custom repositories. If possible, I would suggest using the standard version of junit.

+6
source share

Try a specific context configuration, for example

 @ContextConfiguration(locations = {"/file1.xml", "/file2.xml" }) 

(just showing how this can be used with multiple files if necessary - may be enough)

Edit: Have you enabled AutwiredAnnotationBeanPostProcessor as indicated here? http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

0
source share

I had the same problem. My @Autowire will work in my IDE (SpringSource STS), but will not be able to load the application context when I used Maven to build from the command line.

The problem was my dependencies in pom.xml. I used the Spring JUnit version that caused the error. I think this is the main reason for the original post. I did not need to specify any Maven plugin to work.

I changed

 <dependency> <groupId>org.junit</groupId> <artifactId>com.springsource.org.junit</artifactId> <version>4.7.0</version> </dependency> 

to

 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> 
0
source share

All Articles