我之前见过很多关于此错误的问题,但没有适合我的解决方案。
我是 Spring 新手,但尝试在项目中使用 Spring Data for Neo4J 库。我决定从快速启动开始,以确保我知道一切是如何工作的,因此我设置了一个简单的 App 类,其主要方法如下所示:
package org.example.neo4jSpike;
import org.example.neo4jSpike.domain.Actor;
import org.example.neo4jSpike.repositories.ActorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
/**
* Hello world!
*
*/
@Component
public class App
{
@Autowired
private ActorRepository actors;
@SuppressWarnings("resource")
public static void main( String[] args )
{
ApplicationContext context = new AnnotationConfigApplicationContext(SpikeConfiguration.class);
App a = context.getBean(App.class);
a.init();
}
private void init(){
Actor michaelDouglas = actors.save(new Actor("Michael Douglas"));
System.out.println( "Hello World!" );
System.out.println(michaelDouglas.getId());
System.out.println("Total people: " + actors.count());
}
}
我也有配置类设置:
package org.example.neo4jSpike;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableNeo4jRepositories(basePackages = "org.example.neo4jSpike.repositories")
@EnableTransactionManagement
public class SpikeConfiguration extends Neo4jConfiguration{
@Bean
public SessionFactory getSessionFactory() {
// with domain entity base package(s)
return new SessionFactory("org.example.neo4jSpike.domain");
}
// needed for session in view in web-applications
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
如果需要,我将为我的存储库和域类添加代码,但它们都以类似的方式设置,并且都非常简单。
但是,当我尝试运行 main
时,我得到了
未定义 [org.example.neo4jSpike.App] 类型的合格 bean
我不明白它是如何未定义的,它就在那里,定义为 @Component
。我有什么误解吗?
最佳答案
如果 Spring 没有扫描你的类包,你是否添加 @Component 注释也没有关系。你可以在你的配置类中添加@ComponentScan注解,并配置它扫描你的App类所在的包。或者,您可以删除 @Component 注释并在配置类中声明 App 类型的 Bean。
希望这能有所帮助。
关于java - 运行 main 方法时未定义类型的限定 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37188426/