Spring初始化在项目外部完成
我有一个JavaSpring项目。我看到初始化spring项目的一种方法是在main方法中使用此代码Spring初始化在项目外部完成,spring,maven,spring-mvc,Spring,Maven,Spring Mvc,我有一个JavaSpring项目。我看到初始化spring项目的一种方法是在main方法中使用此代码 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Config.class); ctx.scan("com.example.db.app"); ctx.refresh(); 是否可以将其保留在主方法之外,然
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class);
ctx.scan("com.example.db.app");
ctx.refresh();
是否可以将其保留在主方法之外,然后为该项目制作一个jar。将其作为依赖项添加到其他项目的pom.xml中,并从中调用初始化spring工件的方法
我试过了。我犯了一个错误
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemInformationRepositoryService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.example.db.app.service.ItemInformationRepositoryService.setItemInformationRepositoryService(com.example.db.app.repository.ItemInformationRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.db.app.repository.ItemInformationRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
异常消息声明: 找不到[com.example.db.app.repository.ItemInformationRepository]类型的符合依赖项条件的bean:至少需要1个符合此依赖项autowire候选项条件的bean 这意味着类
com.example.db.app.repository.ItemInformationRepository
不在Spring上下文中。也许您希望Spring发现这个类,因为您指示Spring扫描com.example.db.app
?根据注释ConfigApplicationContext.scan()的Javadocs
在指定的基本包内执行扫描
@param basePackages将包打包以检查带注释的类
因此,为了让Spring发现com.example.db.app.repository.ItemInformationRepository
,您必须:
- 用
org.springframework.stereotype.Component
对其进行注释,以便通过scan()
- 以注册
Config.class
的相同方式注册它,例如ctx.Register(ItemInformationRepository.class)代码>
能否添加一些代码并详细说明问题?您是如何尝试将其移出主方法的?我刚刚创建了一个类,并将所有初始化代码放在一个方法中。创建该类的实例并调用该方法。