Antoine Antoine - 22 days ago 11
Java Question

Spring doesn't instanciate bean at start

I'm stuck with a new problem. My application doesn't create my Services at startup and I end up with a nullPointerException when i try to use them in my Maven Tests after Inject them with @Autowired

I don't understand where it come from. I have done some research but i still don't understand why it doesn't work.

Here is the class where my Autowired "administrationActionService" is null :

public class AdministrationActionTests extends EntityTests {

@Autowired
AdministrationActionService administrationActionService;

@Test
public void equalsTests() {

administrationActionService.getExample();

[...]


The class :

package com.bloombooking.services;
@org.springframework.stereotype.Service
public class AdministrationActionService extends ServiceEntity{

@Autowired private AdministrationActionDao administrationActionDao;

[...]


And my ApplicationContext.xml. I've placed it in src/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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.bloombooking.services, com.bloombooking.dao"/>

</beans>


I really don't know what I could have done wrong, if someone could help me ? Thanks

Answer

to make it work you have make the following changes
1. Add @RunWith(SpringJUnit4ClassRunner.class) to your class.
2. Add @ContextConfiguration("path_to_you_spring_beans.xml")


So your class becomes

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("path_to_you_spring_beans.xml")
AdminisrationActionTests {

}
Comments