2016-08-31 84 views
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..."); 
     } 
} 
+0

值得一讀:http://stackoverflow.com/questions/4703206/spring-autowiring-using-configurable你有某種織造啓用? –

回答

0

你的問題已經包含了答案:「...在非bean類中」。這根本行不通。所有的自動裝配,方面的解決方案,無論如何,只有適用於豆類。因此,你肯定需要通過彈簧廠來構建你的EchoDelegateService:

EchoDelegateService myService = ctx.getBean(EchoDelegateService.class); 
myService.echo("this should really work now"); 
相關問題