Manish Kumar
Manish Kumar

Reputation: 10492

Spring : autowiring inside non spring class

I have this HTTP listener subclass

public class MigificSessionListener implements HttpSessionListener {
    @Autowired
    @Qualifier("notificationThread")
    private NotificationThread notificationThread;  

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
          // here notificationThread value is null
    }
}

Value of notificationThread inside sessionDestroyed() is null.

How can i autowire sessionDestroyed inside this class ?

Upvotes: 0

Views: 2315

Answers (3)

dimitrisli
dimitrisli

Reputation: 21391

Convert your non-Spring managed class MigificSessionListener into a Spring-managed one by annotating it with @Configurable.

For this annotation to be recognised you need <context:spring-configured/> in your Spring XML config or @EnableSpringConfigured if you are using Spring Java config.

The @Autowired or injection of other dependencies will then succeed.

Upvotes: 0

Markus Malkusch
Markus Malkusch

Reputation: 7868

You can enable Spring AOP with @EnableSpringConfigured and annotate your class with @Configurable. This let spring manage instances which are created outside the spring context with new. You will also need to enable either load-time weaving or compile-time weaving. This is documented in 9.8.1 Using AspectJ to dependency inject domain objects with Spring.

@Configuration
@EnableSpringConfigured
public class AppConfig {

}

@Configurable
public class MigificSessionListener implements HttpSessionListener {

    @Autowired
    @Qualifier("notificationThread")
    private NotificationThread notificationThread;

    //...

}

Upvotes: 0

Safrain
Safrain

Reputation: 294

Your MigificSessionListener in not in your spring conext, spring even do not know it exists. You can use WebApplicationContextUtils to get your spring context from ServletContext

WebApplicationContextUtils.getWebApplicationContext(sessionEvent.getSession().getServletContext())

Upvotes: 3

Related Questions