0

I have a unit test and a helper class. Unfortunely the Helper class' autowire does not work. It works fine in MyTest class.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath*:context.xml"})
    @Component
    public class MyTest {

        @Autowired
        private Something something1;

        @Autowired
        private Something something2;
        ..

        @Test
        public void test1()
        {
            // something1 and something2 are fine
            new Helper().initDB();
            ..
        }
   }

// Same package
public class Helper {
   @Autowired
   private Something something1;

   @Autowired
   private Something something2;
   ..

   public void initDB()
    {
        // something1 and something2 are null. I have tried various annotations.
    }
}

I'd like to avoid using setters because I have like 10 of those objects and different tests have different ones. So what is required to get @Autowired working in Helper class? Thx!

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
NoobieNoob
  • 887
  • 2
  • 11
  • 31
  • Possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – kryger Nov 03 '15 at 15:05

2 Answers2

0

Your Helper class is not instanciated by spring ... You have to add an annotation like @component (if you are using package scan), or you can define the class as Bean in your springconfiguration class. But if you create the instance by yourself, it doesn't work

Si mo
  • 969
  • 9
  • 24
0

You must not create the Helper class by a new statement, but you have to let spring create it to become a spring been and therefore its @Autowired fields get injected.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:context.xml"})
@Component
public class MyTest {

    @Autowired
    private Something something1;

    @Autowired
    private Something something2;
    ..

    @Autowired
    private Helper helper

    @Test
    public void test1() {
        helper.initDB();
    }
}


//this class must been found by springs component scann
@Service
public class Helper {
   @Autowired
   private Something something1;

   @Autowired
   private Something something2;

   public void initDB(){...}
}
Ralph
  • 118,862
  • 56
  • 287
  • 383