没有定义名为“”的bean

时间:2018-09-30 13:32:55

标签: java spring aop

我正在Spring中测试简单的AOP用例,但出现以下错误,

  

线程“主”中的异常    org.springframework.beans.factory.NoSuchBeanDefinitionException:否    定义了名为“ bean1”的bean

下面是我的源文件,

  1. DemoConfig.java

    package com.luv2code.aopdemo;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    
    import com.luv2code.aopdemo.aspect.MyDemoLoggingAspect;
    import com.luv2code.aopdemo.dao.AccountDAO;
    
    @Configuration
    @EnableAspectJAutoProxy
    @ComponentScan("com.luv2code.aopdemo")
    public class DemoConfig {
    
        @Bean
        @Qualifier("bean1")
        public AccountDAO accDao() {
            return new AccountDAO();
        }
    
        @Bean
        @Qualifier("bean2")
        public MyDemoLoggingAspect myAscpect() {
            return new MyDemoLoggingAspect();
        }
    }
    
  2. MyDemoLoggingAspect.java

     package com.luv2code.aopdemo.aspect;
    
     import org.aspectj.lang.annotation.Aspect;
     import org.aspectj.lang.annotation.Before;
    
     @Aspect
     public class MyDemoLoggingAspect {
    
        // this is where we add all of our related advices for logging  
        // let's start with an @Before advice
        @Before("execution(** com.luv2code.aopdemo.dao.AccountDAO.addAccount(..))")
        public void beforeAddAccountAdvice() {  
            System.out.println("\n=====>>> Executing @Before advice on addAccount()");
    
        }
     }
    
  3. MainDemoApp.java

    package com.luv2code.aopdemo;
    
    import com.luv2code.aopdemo.dao.AccountDAO;
    
    public class MainDemoApp {
    
        public static void main(String[] args) {
            // read spring config java class
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);          
            // get the bean from spring container
            AccountDAO theAccountDAO = context.getBean("bean1", AccountDAO.class);
            // call the business method
            theAccountDAO.addAccount();
            // do it again!
            System.out.println("\nlet's call it again!\n");
            // call the business method again
            theAccountDAO.addAccount();     
            // close the context
            context.close();
        }
    }
    

即使在Spring无法在上下文中找到我的bean之后,我也给了我自己的bean ID“ bean1”。为什么我会收到此错误以及如何解决此错误?

1 个答案:

答案 0 :(得分:5)

@Qualifier标记与@Autowired注释一起使用。

您需要的是

@Bean(name="bean1")
public AccountDAO accDao() {
    return new AccountDAO();
}