Java Spring @Service @Controller @Repository 错误:创建 bean 时出错

Java Spring error with @Service @Controller @Repository: Error creating bean

拜托,我需要一些帮助,我已经被这个错误困扰了 2 天。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean     with name 'adsController': Unsatisfied dependency expressed through field     'shortUrlService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shortUrlServiceImpl': Unsatisfied dependency expressed through field 'shortUrlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shortUrlRepository' defined in com.codepressed.urlShortener.dao.ShortUrlRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property desc found for type LocalDateTime! Traversed path: ShortUrl.creationDate.

Error display

这是我的代码:

服务class

@Service
public class AdvertisementServiceImpl implements AdvertisementService{

@Autowired
AdvertisementRepository advertisementRepository;

@Autowired
private MongoUtilsService mongoUtilsService;

@Override
public Advertisement save(Advertisement advertisement) {
    advertisement.set_id(mongoUtilsService.getNextValue("AD"));
    return advertisementRepository.insert(advertisement);
}

@Override
public void removeAd(Advertisement advertisement) {
    advertisementRepository.delete(advertisement);
}

@Override
public Advertisement randomAd() {
    List<Advertisement> allAds = advertisementRepository.findAll();
    Random random = new Random();
    return allAds.get(random.nextInt(allAds.size()-1));
}
}

我的资料库

@RepositoryRestResource
public interface AdvertisementRepository extends MongoRepository<Advertisement,Long> {

}

控制器class

@Controller
@RequestMapping("/ad")
public class AdsController {

@Autowired
AdvertisementService advertisementService;

@Autowired
ShortUrlService shortUrlService;

@GetMapping(value="/{id}")
public String getRandomAd(@PathVariable Long id, Model model){
    model.addAttribute("ad", advertisementService.randomAd());
    String url;
    if (shortUrlService.findUrlById(id) != null){
        url = shortUrlService.findUrlById(id);
    }else if (shortUrlService.findUrlByCustom(String.valueOf(id)) != null){
        url = shortUrlService.findUrlByCustom(String.valueOf(id));
    }else {
        url = "/error404.html";
    }
    model.addAttribute("url", url);
    return "go";
        }

我想使用 ServiceImpl 和 Service,但我不知道为什么我不能自动装配它们。 此外,我在配置 Class 上有以下注释: @ComponentScan({"com.codepressed.urlShortener", "com.codepressed.urlShortener.dao", "com.codepressed.urlShortener.service", "com.codepressed.urlShortener.controller"}) 但似乎还不够…… 拜托,任何帮助表示赞赏,我看不到错误或我不明白。

GITHUB 回购:https://github.com/codepressed/Jurly/tree/master/src/main/java/com/codepressed/urlShortener

我刚刚在 github 上克隆了您的代码。

我发现你的方法命名不符合Spring-Data JPA规范。

重命名 ShortUrlRepository 方法:

List<ShortUrl> findFirst10ByCreationDateDesc();

至:

List<ShortUrl> findFirst10ByOrderByCreationDateDesc();

当这个问题解决后,运行应用程序,控制台输出:
No session repository could be auto-configured, check your configuration

所以我创建了一个 mongo http 会话配置:

package com.codepressed.urlShortener.config;

import org.springframework.context.annotation.Bean;
import org.springframework.session.data.mongo.JdkMongoSessionConverter;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;

import java.time.Duration;

@EnableMongoHttpSession
public class HttpSessionConfig {

    @Bean
    public JdkMongoSessionConverter jdkMongoSessionConverter() {
        return new JdkMongoSessionConverter(Duration.ofMinutes(30));
    }
}

然后我运行再次申请,没有异常输出!

2021-06-18 00:06:49.844  INFO 13960 --- [           main] c.c.u.UrlShortenerApplication            : Starting UrlShortenerApplication using Java 11.0.10 on Mashiros-iMac.lan with PID 13960 (/Users/rat/IdeaProjects/Jurly/target/classes started by rat in /Users/rat/IdeaProjects/Jurly)
2021-06-18 00:06:49.850  INFO 13960 --- [           main] c.c.u.UrlShortenerApplication            : No active profile set, falling back to default profiles: default
2021-06-18 00:06:50.295  INFO 13960 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-06-18 00:06:50.329  INFO 13960 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 32 ms. Found 2 MongoDB repository interfaces.
2021-06-18 00:06:50.667  INFO 13960 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-06-18 00:06:50.674  INFO 13960 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-06-18 00:06:50.674  INFO 13960 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.45]
2021-06-18 00:06:50.717  INFO 13960 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-06-18 00:06:50.718  INFO 13960 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 833 ms
2021-06-18 00:06:50.838  INFO 13960 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-06-18 00:06:50.875  INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:1}] to 127.0.0.1:27017
2021-06-18 00:06:50.875  INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:2}] to 127.0.0.1:27017
2021-06-18 00:06:50.876  INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=11069828}
2021-06-18 00:06:51.052  INFO 13960 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:3}] to 127.0.0.1:27017
2021-06-18 00:06:51.067  INFO 13960 --- [           main] o.s.s.d.m.AbstractMongoSessionConverter  : Creating TTL index on field expireAt
2021-06-18 00:06:51.536  INFO 13960 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-06-18 00:06:51.600  INFO 13960 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2021-06-18 00:06:51.891  INFO 13960 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 1c0d09bd-73cc-42aa-8f6a-df157db252fe

2021-06-18 00:06:52.022  INFO 13960 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1e95f584, org.springframework.security.web.context.SecurityContextPersistenceFilter@1a336906, org.springframework.security.web.header.HeaderWriterFilter@39afe59f, org.springframework.security.web.csrf.CsrfFilter@3a3316b6, org.springframework.security.web.authentication.logout.LogoutFilter@57fce8b, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@1b4ba615, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@3a9c11fb, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@54997f67, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@18e8eb59, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@20f63ddc, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@24f177f5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@bf4e48e, org.springframework.security.web.session.SessionManagementFilter@43756cb, org.springframework.security.web.access.ExceptionTranslationFilter@48ee3c2d, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@e6e5da4]
2021-06-18 00:06:52.105  INFO 13960 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-06-18 00:06:52.115  INFO 13960 --- [           main] c.c.u.UrlShortenerApplication            : Started UrlShortenerApplication in 2.542 seconds (JVM running for 3.116)

我觉得你应该参考下面的教程

Spring Session with MongoDB

Sorting Query Results with Spring Data