0
AppConfig包含Java配置。使用AspectJ自動編譯Nonbean類
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是我們有自動裝配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...");
}
}
值得一讀:http://stackoverflow.com/questions/4703206/spring-autowiring-using-configurable你有某種織造啓用? –