![](/img/trans.png)
[英]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.