2017-12-30 12 views
-2

Spring Boot 응용 프로그램을 실행하려고합니다. 처음에는 Application Java에 패키지를 scanBasePackages로 표시하지 않았습니다. 그래서 내 응용 프로그램을 실행하지만 난 그런 문제가 있습니다 Issue With Spring: There was an unexpected error (type=Not Found, status=404) 내가 Application 클래스에서 scanBasePackages를 추가 할 때 내가 얻을 : Autowired가 작동하지 않습니다. 오류 'type of bean'이 필요합니다. '

필드 userService이 fr.umlv.orthopro.controller.UserController 에서 유형의 콩을 요구

' fr.umlv.orthopro.service.UserService '해당 찾을 수 없습니다.

작업 :

이 구성 유형 'fr.umlv.orthopro.service.UserService'의 빈을 정의하는 것이 좋습니다.

그래서 답변을 찾았습니다. 패키지의 배열로 보입니다. 하지만 내가 전에 말했듯이 succes없이 scanBasePackages 주석을 추가하고 수동으로 패키지를 재구성하려고 할 때도 수동으로 작동하지 않습니다. 그래서 많은 시간이 지나면 문제가 어디서 왔는지 파악할 수 없습니다.

내 패키지 구조 :

src/ 
├── main/ 
│ └── java/ 
|  ├── fr.umlv.orthopro.app/ 
|  | └── Application.java 
|  ├── fr.umlv.orthopro.controller/ 
|  | ├── UserController.java 
|  | ├── SentenceController.java 
|  | └── RuleController.java 
|  ├── fr.umlv.orthopro.service/ 
|  | ├── UserService.java 
|  | ├── UserServiceIT.java 
|  | ├── SentenceService.java 
|  | ├── SentenceServiceIT.java 
|  | ├── RuleService.java 
|  | └── RuleServiceIT.java 
|  └── fr.umlv.orthopro.db/ 
|   ├── UserService.java 
|   ├── UserServiceIT.java 
|   └── SentenceService.java 

이 (수입 제외) 내 Application.java 파일

import fr.umlv.orthopro.controller.UserController; 

    @SpringBootApplication(scanBasePackages={"fr.umlv.orthopro.app", "fr.umlv.orthopro.controller", 
      "fr.umlv.orthopro.db", "fr.umlv.orthopro.service"}) 
    @ComponentScan(basePackageClasses=UserController.class) 
    public class OrthoproApp { 
     public static void main(String[] args) throws Exception { 
      SpringApplication.run(OrthoproApp.class, args); 
     } 

     @Bean 
     public CommandLineRunner commandLineRunner(ApplicationContext ctx) { 
      return args -> { 

       System.out.println("Let's inspect the beans provided by Spring Boot:"); 

       String[] beanNames = ctx.getBeanDefinitionNames(); 
       Arrays.sort(beanNames); 
       for (String beanName : beanNames) { 
        System.out.println(beanName); 
       } 

      }; 
     } 
    } 
  • Controller 클래스 (다른 하나는 잠시 비어있는)
입니다
@RestController 
    @Component 
    @RequestMapping("/user") 
    public class UserController { 

     @Autowired 
     private UserService userService; 
     ... 
} 
  • 서비스 클래스 (다른 유사하다) 서비스의
package fr.umlv.orthopro.service; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Propagation; 
import org.springframework.transaction.annotation.Transactional; 

import fr.umlv.orthopro.db.User; 

@Service 
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) 
public abstract class UserService implements UserServiceIT{ 

    @Autowired 
    private UserServiceIT userRepo; 

    @Override 
    public List<User> findAll() { 
     List<User> users = userRepo.findAll(); 
     return users; 
    } 

    @Override 
    public User findById(int id) { 
     User user = userRepo.findOne(id); 
     return user; 
    } 

    @Override 
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false) 
    public User create(String username, String password, String email, String first_name, String last_name, boolean admin) 
        throws NullPointerException, IllegalArgumentException { 
     User new_user = new User(); 

     List<User> userLst = findAll(); 
     for(User tmp_u:userLst) { 

       if(tmp_u.getUsername().equals(username)) 
        throw new IllegalArgumentException("Username alredy exist"); 
     } 
     new_user.setUsername(username); 
     new_user.setEmail(email); 
     new_user.setPassword(password); 
     new_user.setAdmin(admin); 
     new_user.setFirstName(first_name); 
     new_user.setLastName(last_name); 

     new_user = userRepo.save(new_user); 

     if(new_user == null) 
      throw new NullPointerException("Save user has failed"); 

     return new_user; 
    } 

    @Override 
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false) 
    public User update(int id, String username, String password, String email, String first_name, String last_name, Boolean admin) 
        throws NullPointerException { 
     User userToUpdate = findOne(id); 

     if (userToUpdate == null) 
       throw new NullPointerException("Update user by id " + id + " has failed"); 

     if (username != null) 
      userToUpdate.setUsername(username); 
     if (email != null) 
      userToUpdate.setEmail(email); 
     if (password != null) 
      userToUpdate.setPassword(password); 
     if (admin != null) 
      userToUpdate.setAdmin(admin); 
     if (first_name != null) 
      userToUpdate.setFirstName(first_name); 
     if (last_name != null) 
      userToUpdate.setLastName(last_name); 


     User updatedUser = userRepo.save(userToUpdate); 
     if (updatedUser == null) 
       throw new NullPointerException("Save updated user by id " + id + " has failed"); 

      return updatedUser; 
    } 

    @Override 
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false) 
    public void delete(int id) throws IllegalArgumentException { 
     try { 
      userRepo.delete(id); 
     } 
     catch(IllegalArgumentException e) { 
      throw new IllegalArgumentException("Save updated user by id " + id + " has failed", e); 
     } 
    } 
} 
  • 내 인터페이스
package fr.umlv.orthopro.service; 

import java.util.List; 

import org.springframework.data.jpa.repository.JpaRepository; 
import fr.umlv.orthopro.db.User; 

public interface UserServiceIT extends JpaRepository<User, Integer>{ 

    List<User> findAll(); 

    User findById(int id); 

    User create(String username, String password, String email, String first_name, String last_name, boolean admin) 
      throws NullPointerException, IllegalArgumentException; 

    User update(int id, String username, String password, String email, String first_name, String last_name, Boolean admin) 
      throws NullPointerException ; 

    void delete(int id) throws IllegalArgumentException; 

} 

내 로그

[INFO] Scanning for projects... 
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for fr.umlv.orthopro:OrthoPro_brain:jar:1.0-SNAPSHOT 
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.hibernate:hibernate-c3p0:jar -> duplicate declaration of version 5.2.12.Final @ line 138, column 19 
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. 
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects. 
[WARNING] 
[INFO] 
[INFO] ------------------------------------------------------------------------ 
[INFO] Building OrthoPro_brain 1.0-SNAPSHOT 
[INFO] ------------------------------------------------------------------------ 
[INFO] 
[INFO] >>> spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) > test-compile @ OrthoPro_brain >>> 
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ OrthoPro_brain --- 
[INFO] Using 'UTF-8' encoding to copy filtered resources. 
[INFO] Copying 0 resource 
[INFO] Copying 1 resource 
[INFO] 
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ OrthoPro_brain --- 
[INFO] Nothing to compile - all classes are up to date 
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ OrthoPro_brain --- 
[INFO] Using 'UTF-8' encoding to copy filtered resources. 
[INFO] skip non existing resourceDirectory /Users/Unconnu/Desktop/orthopro/OrthoPro_brain/src/test/resources 
[INFO] 
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ OrthoPro_brain --- 
[INFO] Nothing to compile - all classes are up to date 
[INFO] 
[INFO] <<< spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) < test-compile @ OrthoPro_brain <<< 
[INFO] 
[INFO] 
[INFO] --- spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) @ OrthoPro_brain --- 

    . ____   _   __ _ _ 
/\\/___'_ __ _ _(_)_ __ __ _ \ \ \ \ 
(()\___ | '_ | '_| | '_ \/ _` | \ \ \ \ 
\\/ ___)| |_)| | | | | || (_| | )))) 
    ' |____| .__|_| |_|_| |_\__, |//// 
=========|_|==============|___/=/_/_/_/ 
:: Spring Boot ::  (v1.5.9.RELEASE) 

2017-12-30 19:51:29.818 INFO 13291 --- [   main] fr.umlv.orthopro.OrthoproApp    : Starting OrthoproApp on MacBook-Pro-de-Unconnu.local with PID 13291 (/Users/Unconnu/Desktop/orthopro/OrthoPro_brain/target/classes started by Unconnu in /Users/Unconnu/Desktop/orthopro/OrthoPro_brain) 
2017-12-30 19:51:29.821 INFO 13291 --- [   main] fr.umlv.orthopro.OrthoproApp    : No active profile set, falling back to default profiles: default 
2017-12-30 19:51:29.944 INFO 13291 --- [   main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]17fd8a8c: startup date [Sat Dec 30 19:51:29 CET 2017]; root of context hierarchy 
2017-12-30 19:51:35.325 INFO 13291 --- [   main] org.xnio         : XNIO version 3.3.8.Final 
2017-12-30 19:51:35.359 INFO 13291 --- [   main] org.xnio.nio        : XNIO NIO Implementation Version 3.3.8.Final 
2017-12-30 19:51:35.448 WARN 13291 --- [   main] io.undertow.websockets.jsr    : UT026009: XNIO worker was not set on WebSocketDeploymentInfo, the default worker will be used 
2017-12-30 19:51:35.449 WARN 13291 --- [   main] io.undertow.websockets.jsr    : UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used 
2017-12-30 19:51:35.532 INFO 13291 --- [   main] io.undertow.servlet      : Initializing Spring embedded WebApplicationContext 
2017-12-30 19:51:35.533 INFO 13291 --- [   main] o.s.web.context.ContextLoader   : Root WebApplicationContext: initialization completed in 5596 ms 
2017-12-30 19:51:35.813 INFO 13291 --- [   main] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 
2017-12-30 19:51:35.883 INFO 13291 --- [   main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 
2017-12-30 19:51:35.884 INFO 13291 --- [   main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 
2017-12-30 19:51:35.884 INFO 13291 --- [   main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 
2017-12-30 19:51:35.885 INFO 13291 --- [   main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 
2017-12-30 19:51:37.559 INFO 13291 --- [   main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 
2017-12-30 19:51:37.649 INFO 13291 --- [   main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ 
    name: default 
    ...] 
2017-12-30 19:51:37.989 INFO 13291 --- [   main] org.hibernate.Version     : HHH000412: Hibernate Core {5.2.12.Final} 
2017-12-30 19:51:37.991 INFO 13291 --- [   main] org.hibernate.cfg.Environment   : HHH000206: hibernate.properties not found 
2017-12-30 19:51:38.127 INFO 13291 --- [   main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 
2017-12-30 19:51:38.513 INFO 13291 --- [   main] org.hibernate.dialect.Dialect   : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect 
2017-12-30 19:51:38.691 INFO 13291 --- [   main] o.h.e.j.e.i.LobCreatorBuilderImpl  : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 
2017-12-30 19:51:41.379 INFO 13291 --- [   main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hiber[email protected]23fb847f' 
2017-12-30 19:51:41.410 INFO 13291 --- [   main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 
2017-12-30 19:51:41.508 WARN 13291 --- [   main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'fr.umlv.orthopro.service.UserServiceIT' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
2017-12-30 19:51:41.508 INFO 13291 --- [   main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 
2017-12-30 19:51:41.509 INFO 13291 --- [   main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed drop of schema as part of SessionFactory shut-down' 
2017-12-30 19:51:41.572 INFO 13291 --- [   main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 
2017-12-30 19:51:42.193 ERROR 13291 --- [   main] o.s.b.d.LoggingFailureAnalysisReporter : 

*************************** 
APPLICATION FAILED TO START 
*************************** 

Description: 

Field userService in fr.umlv.orthopro.controller.UserController required a bean of type 'fr.umlv.orthopro.service.UserServiceIT' that could not be found. 


Action: 

Consider defining a bean of type 'fr.umlv.orthopro.service.UserServiceIT' in your configuration. 

[WARNING] 
java.lang.reflect.InvocationTargetException 
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) 
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) 
    at java.base/java.lang.Thread.run(Thread.java:844) 
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'fr.umlv.orthopro.service.UserServiceIT' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) 
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) 
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) 
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) 
    at fr.umlv.orthopro.OrthoproApp.main(OrthoproApp.java:15) 
    ... 6 more 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'fr.umlv.orthopro.service.UserServiceIT' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) 
    ... 25 more 
[INFO] ------------------------------------------------------------------------ 
[INFO] BUILD FAILURE 
[INFO] ------------------------------------------------------------------------ 
[INFO] Total time: 24.029 s 
[INFO] Finished at: 2017-12-30T19:51:42+01:00 
[INFO] Final Memory: 34M/112M 
[INFO] ------------------------------------------------------------------------ 
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project OrthoPro_brain: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'fr.umlv.orthopro.service.UserServiceIT' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} -> [Help 1] 
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. 
[ERROR] Re-run Maven using the -X switch to enable full debug logging. 
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles: 
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException 
+0

당신은이 찾고있는 무슨 인'UserService'에 대한 코드를 보여 무시. –

+0

감사합니다. 내 게시물을 편집했습니다. 자세한 내용이 필요하면 알려주십시오. – Unconnu

답변

1
  1. @RestController는 @ controller + @ ResponseBoby의 조합입니다. @RestController를 언급하면 ​​각 메소드에 대해 @component 및 @ResponseBody를 언급 할 필요가 없습니다.
  2. @SpringBootApplication (scanBasePackages =, 언급 한 패키지를 검사 할 때 @ComponentScan을 따로 언급하지 않아도 됨) 3. 패키지 구조에서 2 개의 UserService.java를 볼 수 있습니다. 제대로 가져 왔는지 확인하십시오.

감사합니다, 디비는

0

012 제거in UserService 클래스는 @Service이 (가) 저장소가 아닙니다. UserServiceITUserRepository으로 변경하고 @Repository 주석을 추가하는 것도 좋습니다.

+0

UserService 클래스가 JpaRepository를 직접 확장하여'save''delete' 등을 사용해야합니까? – Unconnu

+0

이 메소드를 서비스 클래스에서 직접 사용하고 싶지는 않습니다. 대신 autowired'userRepo' 필드를 사용하십시오. –

+0

[예제] (https://javabeat.net/spring-data-jpa/)를 확인하십시오. 적절한 접근 방식을 보여줍니다 (Repository -> Service -> Controller>). 희망은 내가 도움이되었다 –

관련 문제