[英]Spring @Resource Expected at least 1 bean which qualifies as autowire candidate for this dependency
[英]Spring expected at least 1 bean which qualifies as autowire candidate for this dependency
我使用Spring和Hibernate和我想的是,为了是必要的自动装配服务内部信息库“线”的类。
Repository 类扩展了 CrudRepository
停止存储库
@Repository
@RepositoryRestResource(collectionResourceRel = "stop", path = "stop")
public interface StopRepository extends CrudRepository<StopJPA, Long> {
StopJPA findById(@Param("id") Long id);
StopJPA findByIdStop(@Param("idStop") String idStop);
@Override
void delete(StopJPA deleted);
@Override
List<StopJPA> findAll();
// Optional<StopJPA> findOne(Long id);
@Override
StopJPA findOne(Long id);
@Override
StopJPA save(StopJPA persisted);
void flush();
}
实体类。
停止JPA
@Entity
@Table(name = "stop")
@EntityListeners(RepoListener.class)
public class StopJPA implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "stop_description")
private String stopDescription;
@Column(name = "id_stop", nullable = false)
private String idStop;
public StopJPA() {
}
public StopJPA(String stopDescription, String idStop) {
this.stopDescription = stopDescription;
this.idStop = idStop;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStopDescription() {
return stopDescription;
}
public void setStopDescription(String stopDescription) {
this.stopDescription = stopDescription;
}
public String getIdStop() {
return idStop;
}
public void setIdStop(String idStop) {
this.idStop = idStop;
}
}
和服务类实现:
停止服务
@Service
final class RepoStopService {
@Service
final class RepoStopService {
private final StopRepository stopRepository;
@Autowired
RepoStopService(StopRepository stopRepository) {
this.stopRepository = stopRepository;
}
}
不幸的是,当我尝试在服务器上运行它时,出现此异常:
严重:异常将上下文初始化事件发送到类的侦听器实例
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“repoStopService”的 bean 时出错,在文件 ...\\RepoStopService.class 中定义:
通过构造函数参数表示不满意的依赖项,类型为 [com.project.app.services.repositories.StopRepository]: :找不到类型为[com.project.app.services.repositories.StopRepository] 的合格 bean依赖项:预期在至少 1 个 bean 有资格作为此依赖项的自动装配候选者。 依赖注解:{};嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [com.project.app.services.repositories.StopRepository] 的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。 依赖注解:{} at .....
有谁知道为什么 Spring 不接受@Repository注释?
我的配置包含 3 个文件。 一个AppInitializer类实现WebApplicationInitializer,扩展WebMvcConfigurerAdapter和最后一个PersistentContext类WebMvcConfig类。
应用初始化器
public class AppInitializer implements WebApplicationInitializer {
private static final String CONFIG_LOCATION = "com.project.app.config";
private static final String MAPPING_URL = "/";
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Create the 'root' Spring application context
WebApplicationContext context = getContext();
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(context));
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(MAPPING_URL);
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(CONFIG_LOCATION);
return context;
}
WebMvcConfig
@EnableWebMvc
@Configuration
//@EnableJpaRepositories
@ComponentScan(basePackages = { "com.project.app" })
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private Environment env;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("hello");
}
@Bean
public ApplicationContextProvider applicationContextProvider() {
return new ApplicationContextProvider();
}
}
持久上下文
@Component
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistenceContext {
@Autowired
private Environment env;
@Bean
@Primary
public DataSource dataSource() throws ClassNotFoundException {
DataSource ds = new DataSource();
String url = env.getProperty(SystemSettings.AMTAB_DS_URL);
String user = env.getProperty(SystemSettings.AMTAB_DS_USERNAME);
String pass = env.getProperty(SystemSettings.AMTAB_DS_PASSWORD);
String driver = env.getProperty(SystemSettings.AMTAB_DS_DRIVER);
// ds.setDriverClassName("org.postgresql.Driver");
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(pass);
return ds;
}
@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("com.project.app.services.entities");
Properties jpaProperties = new Properties();
// Configures the used database dialect. This allows Hibernate to create SQL
// that is optimized for the used database.
jpaProperties.put("hibernate.dialect",
env.getRequiredProperty(SystemSettings.HIBERNATE_DIALECT));
// Specifies the action that is invoked to the database when the Hibernate
// SessionFactory is created or closed.
jpaProperties.put("hibernate.hbm2ddl.auto",
env.getRequiredProperty(SystemSettings.HIBERNATE_HBM2DDL));
// Configures the naming strategy that is used when Hibernate creates
// new database objects and schema elements
// jpaProperties.put("hibernate.ejb.naming_strategy",
// env.getRequiredProperty(SystemSettings.HIBERNATE_NAMING_STRATEGY));
// If the value of this property is true, Hibernate writes all SQL
// statements to the console.
jpaProperties.put("hibernate.show_sql",
env.getRequiredProperty(SystemSettings.HIBERNATE_SHOW_SQL));
// If the value of this property is true, Hibernate will format the SQL
// that is written to the console.
jpaProperties.put("hibernate.format_sql",
env.getRequiredProperty(SystemSettings.HIBERNATE_FORMAT_SQL));
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
/**
* Because we are using JPA, we have to create a transaction manager bean that integrates the
* JPA provider with the Spring transaction mechanism. We can do this by using the
* JpaTransactionManager class as the transaction manager of our application.
*
* We can configure the transaction manager bean by following these steps:
*
* -> Create a new JpaTransactionManager object. -> Configure the entity manager factory whose
* transactions are managed by the created JpaTransactionManager object.
**/
@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
解决方案
我只是需要还可以指定库的包,因为这不会被默认搜索其位置- > @EnableJpaRepositories(“com.project.app.services.repositories”)
在使用Spring Data时 ,必须在@Configuration
类上声明@ComponentScan
和@EnableJpaRepositories
注释。
关于@EnableJpaRepositories
javadoc :
用于启用JPA存储库的注释。 默认情况下,将扫描Spring Data存储库的带注释配置类的包。
如果您在使用存储库类作为自动装配时遇到此错误。 您只需要根据您的存储库类使用以下注释。
Mongo 存储库:@EnableMongoRepositories("spring.mongorestapi.repositories")
JPA 存储库:@EnableJPARepositories("spring.jparestapi.repositories")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.