0

AppConfig contains Java Configuration.

package com.wh;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;

@Configuration
@EnableSpringConfigured
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
public class AppConfig {

    @Bean
    @Lazy
    public EchoService echoService(){

          return new EchoService();
    }
@Bean
    public InstrumentationLoadTimeWeaver loadTimeWeaver()  throws Throwable {
    InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
    return loadTimeWeaver;
    }
}

Service Class

package com.wh;

import org.springframework.stereotype.Service;

@Service
public class EchoService {
    public void echo( String s ) {
        System.out.println( s );
    }
}

EchoDelegateService is the Non Bean class in which we have Autowired The required Bean. We expect that the EchoService should get autowired.

Problem : EchoService not getting autowired. Gives an Null Pointer exception.

package com.wh;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

@Configurable( preConstruction = true, autowire = Autowire.BY_TYPE, dependencyCheck = false )
public class EchoDelegateService {
    @Autowired
    private EchoService echoService;

    public void echo( String s ) {
        echoService.echo( s );
    }
}

Main Class where we are calling method of NonBean Class.

package com.wh;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
    public static void main(String[] args) {
          ApplicationContext ctx = 
          new AnnotationConfigApplicationContext(AppConfig.class);

          new EchoDelegateService().echo("hihi, it works...");
       }
}
Akshay Jain
  • 73
  • 2
  • 8
  • worth a read: http://stackoverflow.com/questions/4703206/spring-autowiring-using-configurable Do you have some kind of weaving enabled? –  Aug 31 '16 at 05:28

1 Answers1

0

Your question already includes the answer: "... in a non-bean class". This simply does not work. All the autowiring, aspect resolving and whatever is to that, only works for beans. Thus, you definitely need to construct your EchoDelegateService via the spring factory:

EchoDelegateService myService = ctx.getBean(EchoDelegateService.class);
myService.echo("this should really work now");
mtj
  • 3,381
  • 19
  • 30