没有定义名为''的bean

Mar*_*rts 0 java aop spring

我正在测试Spring中的简单AOP用例,但是我得到了以下错误,

线程"main"中的异常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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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()");
    
        }
     }
    
    Run Code Online (Sandbox Code Playgroud)
  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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

我已经给出了我的bean ID"bean1",即使在Spring无法在上下文中找到我的bean之后也是如此.为什么我会收到此错误以及如何解决此问题?

小智 5

@Qualifier标签是用来与@Autowired注解.

你需要的是什么

@Bean(name="bean1")
public AccountDAO accDao() {
    return new AccountDAO();
}
Run Code Online (Sandbox Code Playgroud)