这让我疯了。我有以下文件,这是一个非常简单的设置。
public class MainApp {
public static void main(String[] args) {
//read the spring config java class
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("Config.class");
//System.out.println("Bean names: " + Arrays.toString(context.getBeanNamesForType(AccountDAO.class)));
//get the bean from spring container
AccountDAO accountDAO = context.getBean("accountDAO", AccountDAO.class);
//call the business method
accountDAO.addAccount();
//close the spring context
context.close();
}
}
Config.java:
@Configuration
@ComponentScan("com.aop")
@EnableAspectJAutoProxy
public class Config {
}
LoggingAspectDemo.java:
@Aspect
@Component
public class LoggingAspectDemo {
//this is where we add all our related advices for the logging
//let's start with an @Before advice
@Before("execution(public void addAccount())")
public void beforeAddAccountAdvice() {
System.out.println("\n=======>>>> Executing @Before advice on method addAccount() <<<<========");
}
}
AccountDAO.java
@Component
public class AccountDAO {
public void addAccount() {
System.out.println(getClass() + ": Doing my Db work: Adding an account");
}
}
每次我运行MainApp.java时,我都会得到:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'accountDAO' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
所有文件都在&#34; com.aop&#34;包所以@ComponentScan应该扫描所有组件。它看起来很简单但是我无法解决问题,任何人都可以在我出错的地方帮助我吗?
答案 0 :(得分:1)
您正在使用AnnotationConfigApplicationContext
作为String参数调用"Config.class"
的构造函数,但此构造函数实际上是用于调用base packages,即参数必须是包名。
由于您希望将它与Configuration类一起使用,请使用构造函数which accepts Class instance,即。
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);