简体   繁体   中英

Spring doesn't instantiate bean at start

I'm stuck with the following 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 comes 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. Can someone help me? Thanks!

To make it work you have to 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")
AdministrationActionTests {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM