AppConfig包含Java配置。
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;
}
}
服务类
package com.wh;
import org.springframework.stereotype.Service;
@Service
public class EchoService {
public void echo( String s ) {
System.out.println( s );
}
}
EchoDelegateService是Non Bean类,我们在其中使用Autowired所需的Bean。 我们希望EchoService可以自动连接。
问题:EchoService未获得自动装配。给出空指针异常。
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 );
}
}
我们正在调用NonBean类的方法的主类。
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...");
}
}
答案 0 :(得分:0)
你的问题已经包含了答案:“......在非豆类中”。这根本行不通。所有自动装配,方面解决以及任何内容,仅适用于bean。因此,您肯定需要通过spring factory构建您的EchoDelegateService:
EchoDelegateService myService = ctx.getBean(EchoDelegateService.class);
myService.echo("this should really work now");