【发布时间】:2016-08-31 04:07:30
【问题描述】:
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 是非 Bean 类,我们在其中自动装配了所需的 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...");
}
}
【问题讨论】:
-
值得一读:stackoverflow.com/questions/4703206/…您是否启用了某种编织功能?