2016-08-15 84 views
0

我正在學習由Craig Walls編寫的Spring in Action第四版。我試圖應用通知接口聲明的方法,我得到異常。當我將相同的建議應用於沒有實現任何內容的類時,一切正常。Spring AOP不能對接口應用建議

春季版 - 4.3.2

幫助將不勝感激。

例外:

Exception in thread "main"org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.fifczan.bean.UserService] is defined 

代碼:

接口:

package com.fifczan.bean; 

public interface Service { 

void doTask(); 
} 

實現:

package com.fifczan.bean; 

import org.springframework.stereotype.Component; 


@Component 
public class UserService implements Service { 


public void doTask() { 

    System.out.println("doing task"); 

} 
} 

看點:

package com.fifczan; 

import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before; 
import org.springframework.stereotype.Component; 

@Aspect 
@Component 
public class UserAspect { 

//If i change Service(interface) to UserService(implementation) 
//in pointcut I am getting the same exception 
@Before("execution(* com.fifczan.bean.Service.doTask(..))") 
public void userAdvice(){ 
    System.out.println("doing sth before method doTask"); 
} 
} 

配置:

package com.fifczan; 

import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.annotation.EnableAspectJAutoProxy; 


@Configuration 
@EnableAspectJAutoProxy 
@ComponentScan 
public class AspectJAutoProxyConfig { 

} 

主:

package com.fifczan; 
import org.springframework.context.annotation.AnnotationConfigApplicationContext; 
import com.fifczan.bean.UserService; 

public class AspectJAutoProxyTest { 
public static void main(String[] args) { 

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AspectJAutoProxyConfig.class); 

    UserService userService= ctx.getBean(UserService.class); 
    userService.doTask(); 
    } 
} 

回答

0

你問的UserService豆,這是具體類,而不是接口 。檢索或注入類型Service的豆。

+0

謝謝,這解決了我的問題 –