0

I want to be able to Autowire generic DAO services in instances that will be created by calls to new()... in my java code. I understood the @configurable is the right way to go looking at This spring doc.

So here is my class code

@Configurable(dependencyCheck=true)
public class DynVdynOperationsImpl implements DynVdynOperations {

    @Autowired
    private DynVdynInDbDao vdynDao;

I want to use it in a Junit test with spring test which looks like this

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { xxx.MainConfig.class })
@ActiveProfiles({ "database-test", "classpath" })
public class DynVdynOperationsImplTest {

   @Test
   public void testSend() {
   underTest = new DynVdynOperationsImpl();
   underTest.sendVdyn("0254", null, null);
   ... }

The main config class looks like that,

@Configuration
@EnableSpringConfigured
@ComponentScan(basePackages = {xxx })
public class MainConfig {
...
    @Bean
    @Scope("prototype")
    public DynVdynOperations vdynOperations () {
        return new DynVdynOperationsImpl();
    }

executing the test, the undertest vdynDao properties is not autowired properly and remains null. Looking at this similar question, I might be missing things regarding AspectJ in my config.

Is there a simple way to make it work? i.e a one where I do not feel like using a hammer to kill a fly compared to inject myself in my code the dao when creating the object? May be calling the spring bean factory directly from my code inside a @Service object?

Community
  • 1
  • 1
Yves Nicolas
  • 6,901
  • 7
  • 25
  • 40

2 Answers2

0

Try putting an @Scope("prototype") on the class definition of DynVdynOperationsImpl.

Additionally, instead of "new DynVdynOperationsImpl", I think you need to name the bean (i.e. "DynVdynOperations") and then use: applicationContext.getBean("DynVdynOperations") to create a new instance of it. Using getBean will tell Spring to handle the wiring that it finds.

Jeff Bennett
  • 996
  • 7
  • 18
0

Here seems to be the best and simple way to do it. Avoids the complexity of using AspectJ.

Config class is fine. Declaring the bean with a @Scope("prototype") makes sure a new instance is created everytime we ask Spring to get a bean of this class.

In the test class, ask Spring Container to produce the bean using the Application context :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { xxx.MainConfig.class })
@ActiveProfiles({ "database-test", "classpath" })
public class DynVdynOperationsImplTest {

   @Autowired
   ApplicationContext context;

   @Test
   public void testSend() {
   underTest = context.getBean(DynVdynOperations.class);
   underTest.sendVdyn("0254", null, null);
   ... }
Yves Nicolas
  • 6,901
  • 7
  • 25
  • 40