Question

I have a class that gets created within server startup. It serves as entry method for the client application. I cannot change this behaviour.

Though I'd like to use Spring @Autowired inside this unmanaged class. I read that aspectj weaving might be the way to go. It seems to already execute accoding to logs:

2014-01-28 13:11:10,156 INFO org.springframework.context.weaving.DefaultContextLoadTimeWeaver: Using a reflective load-time weaver for class loader: org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader

But still my injected Dao service is null. What might be missing?

@WebListener
public class MyContextListener implements ServletContextListener {
        @Override
            public void contextInitialized(ServletContextEvent sce) {
            new TestService().run(); //throws NPE
        }
}

@Configurable
class TestService extends AbstractLegacyService {       
    @Autowired
    private Dao dao;

    @Override
    public void run() {
        //dao is always null
        dao.find();
    }
}


@Component
class Doa dao;

enable weaving (tomcat):

@Configuration
@EnableLoadTimeWeaving
@EnableSpringConfigured
public class AppConfig {
}
Was it helpful?

Solution

You must make sure that the ContextLoaderListener is invoked before the MyContextListener gets invoked.

The ContextLoaderListener initializes the spring container and the load-time weaver can only inject the dependencies of the TestService if the spring container is initialized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top