Getting UnsatisfiedDependency exception(No qualifying bean of type found) even though bean is defined and using Service annotation

huangapple go评论102阅读模式
英文:

Getting UnsatisfiedDependency exception(No qualifying bean of type found) even though bean is defined and using Service annotation

问题

@RestController
@RequestMapping(ProjectRestController.ENDPOINT)
@Api(produces = MediaType.APPLICATION_JSON_VALUE, tags = "项目")
public class ProjectRestController {

	public static final String ENDPOINT = "/api/v2/projects";
	public static final String ENDPOINT_ID = "/{id}";
	public static final String PATH_VARIABLE_ID = "id";
	public static final String ENDPOINT_SYSTEM_ID = "/{systemId}/projects";

	private static final String API_PARAM_ID = "ID";
    
	@Autowired
	private SdlcService sdlcService;

	@Autowired
	private ProjectService projectService;

	@ApiOperation("获取项目")
	@GetMapping(ENDPOINT_ID)
	public Project getProject(
			@ApiParam(name = API_PARAM_ID, required = true) @PathVariable(PATH_VARIABLE_ID) final long projectId) {
		return projectService.getProject(projectId);
	}

	@ApiOperation("创建项目")
	@PostMapping(ENDPOINT_SYSTEM_ID)
	public Project createProject(@PathVariable(value = "systemId") Long systemId, @Valid @RequestBody Project project) {
		sdlcService.findById(systemId).ifPresent(project::setSdlcSystem);
		return projectService.saveProject(project);
	}
}
@Entity
@lombok.Data
@Table(name = "project")
@EntityListeners(AuditingEntityListener.class)
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Column(name = "external_id", nullable = false)
    @NotBlank
    private String externalId;

    public String getExternalId() {
        return this.externalId;
    }

    public void setExternalId(String externalId) {
        this.externalId = externalId;
    }

    @Column(name = "name")
    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToOne
    @JoinColumn(name = "sdlc_system_id")
    @NotNull
    private SdlcSystem sdlcSystem;

    public SdlcSystem getSdlcSystem() {
        return this.sdlcSystem;
    }

    public void setSdlcSystem(SdlcSystem sdlcSystem) {
        this.sdlcSystem = sdlcSystem;
    }

    @Column(name = "created_date", nullable = false)
    @CreatedDate
    private Instant createdDate;

    public Instant getCreatedDate() {
        return this.createdDate;
    }

    public void setCreatedDate(Instant createdDate) {
        this.createdDate = createdDate;
    }

    @Column(name = "last_modified_date", nullable = false)
    @LastModifiedDate
    private Instant lastModifiedDate;

    public Instant getLastModifiedDate() {
        return this.lastModifiedDate;
    }

    public void setLastModifiedDate(Instant lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

}
@Data
@Entity
@Table(name = "sdlc_system")
@EntityListeners(AuditingEntityListener.class)
public class SdlcSystem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotEmpty
    @URL
    @Column(name = "base_url", nullable = false)
    private String baseUrl;

    public String getBaseUrl() {
        return this.baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @Column(name = "description")
    private String description;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Column(name = "created_date", nullable = false)
    @CreatedDate
    private Instant createdDate;

    public Instant getCreatedDate() {
        return this.createdDate;
    }

    public void setCreatedDate(Instant createdDate) {
        this.createdDate = createdDate;
    }

    @Column(name = "last_modified_date", nullable = false)
    @LastModifiedDate
    private Instant lastModifiedDate;

    public Instant getLastModifiedDate() {
        return this.lastModifiedDate;
    }

    public void setLastModifiedDate(Instant lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

}
@Repository
public interface ProjectRepository extends JpaRepository<Project, Long> {

    Optional<Project> findBySdlcSystemIdAndId(long sdlcSystemId, long projectId);

    Optional<Project> findById(long projectId);

}
@Repository
public interface SdlcSystemRepository extends JpaRepository<SdlcSystem, Long> {

    Optional<SdlcSystem> findById(long systemId);

}
@Service
public interface ProjectService {

    Project getProject(long id);

    Project saveProject(Project project);
}
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private ProjectRepository projectRepository;

	public Project getProject(long id) {
		return projectRepository.findById(id).orElseThrow(
				() -> new RuntimeException("找不到类" + Project.class + "和 id:" + id));
	}

	public Project saveProject(Project project) {
		try {
			return projectRepository.save(project);
		} catch (Exception e) {
			return null;
		}
	}

}
@Service
public interface SdlcService {

    Optional<SdlcSystem> findById(Long systemId);
}
public class SdlcServiceImpl {

    @Autowired
    private SdlcSystemRepository sdlcSystemRepository;

    SdlcSystem findById(Long systemId) {
        return sdlcSystemRepository.findById(systemId).orElseThrow(
                () -> new RuntimeException("找不到类" + SdlcSystem.class + "和 id:" + systemId));
    }
}
@SpringBootApplication
public class RestapiApplication {

	public static void main(String[] args) {
		SpringApplication.run(RestapiApplication.class, args);
	}
}
英文:

I am trying to run my basic restapi application which has some pojo defined and using service layer to fetch data from h2 database. But when i run the application, i am getting bean not found for one of the service object.

ProjectResController.java

    @RestController
@RequestMapping(ProjectRestController.ENDPOINT)
@Api(produces = MediaType.APPLICATION_JSON_VALUE, tags = &quot;Project&quot;)
public class ProjectRestController {
public static final String ENDPOINT = &quot;/api/v2/projects&quot;;
public static final String ENDPOINT_ID = &quot;/{id}&quot;;
public static final String PATH_VARIABLE_ID = &quot;id&quot;;
public static final String ENDPOINT_SYSTEM_ID = &quot;/{systemId}/projects&quot;;
private static final String API_PARAM_ID = &quot;ID&quot;;
@Autowired
private SdlcService sdlcService;
@Autowired
private ProjectService projectService;
@ApiOperation(&quot;Get a Project&quot;)
@GetMapping(ENDPOINT_ID)
public Project getProject(
@ApiParam(name = API_PARAM_ID, required = true) @PathVariable(PATH_VARIABLE_ID) final long projectId) {
return projectService.getProject(projectId);
}
@ApiOperation(&quot;Create a Project&quot;)
@PostMapping(ENDPOINT_SYSTEM_ID)
public Project createProject(@PathVariable(value = &quot;systemId&quot;) Long systemId, @Valid @RequestBody Project project) {
sdlcService.findById(systemId).ifPresent(project::setSdlcSystem);
return projectService.saveProject(project);
}
}

Project.java

    @Entity
@lombok.Data
@Table(name = &quot;project&quot;)
@EntityListeners(AuditingEntityListener.class)
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = &quot;external_id&quot;, nullable = false)
@NotBlank
private String externalId;
public String getExternalId() {
return this.externalId;
}
public void setExternalId(String externalId) {
this.externalId = externalId;
}
@Column(name = &quot;name&quot;)
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
@JoinColumn(name = &quot;sdlc_system_id&quot;)
@NotNull
private SdlcSystem sdlcSystem;
public SdlcSystem getSdlcSystem() {
return this.sdlcSystem;
}
public void setSdlcSystem(SdlcSystem sdlcSystem) {
this.sdlcSystem = sdlcSystem;
}
@Column(name = &quot;created_date&quot;, nullable = false)
@CreatedDate
private Instant createdDate;
public Instant getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
@Column(name = &quot;last_modified_date&quot;, nullable = false)
@LastModifiedDate
private Instant lastModifiedDate;
public Instant getLastModifiedDate() {
return this.lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}

SdlcSystem.java

    @Data
@Entity
@Table(name = &quot;sdlc_system&quot;)
@EntityListeners(AuditingEntityListener.class)
public class SdlcSystem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotEmpty
@URL
@Column(name = &quot;base_url&quot;, nullable = false)
private String baseUrl;
public String getBaseUrl() {
return this.baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Column(name = &quot;description&quot;)
private String description;
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = &quot;created_date&quot;, nullable = false)
@CreatedDate
private Instant createdDate;
public Instant getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
@Column(name = &quot;last_modified_date&quot;, nullable = false)
@LastModifiedDate
private Instant lastModifiedDate;
public Instant getLastModifiedDate() {
return this.lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}

ProjectRepository.java


@Repository
public interface ProjectRepository extends JpaRepository&lt;Project, Long&gt; {
Optional&lt;Project&gt; findBySdlcSystemIdAndId(long sdlcSystemId, long projectId);
Optional&lt;Project&gt; findById(long projectId);
}

SdlcsystemRepository.java

@Repository
public interface SdlcSystemRepository extends JpaRepository&lt;SdlcSystem, Long&gt; {
Optional&lt;SdlcSystem&gt; findById(long systemId);
}```
**ProjectService.java**
@Service

public interface ProjectService {

Project getProject(long id);
Project saveProject(Project project);

}

**ProjectServiceImpl.java**
```   public class ProjectServiceImpl implements ProjectService {
@Autowired
private ProjectRepository projectRepository;
public Project getProject(long id) {
return projectRepository.findById(id).orElseThrow(
() -&gt; new RuntimeException(&quot;Value Not found for class&quot; + Project.class + &quot; and id: &quot; + id));
}
public Project saveProject(Project project) {
try {
return projectRepository.save(project);
} catch (Exception e) {
return null;
}
}
}

SdlcService.java

    @Service
public interface SdlcService {
Optional&lt;SdlcSystem&gt; findById(Long systemId);
}

SdlcServiceImpl.java

public class SdlcServiceImpl {
@Autowired
private SdlcSystemRepository sdlcSystemRepository;
SdlcSystem findById(Long systemId) {
return sdlcSystemRepository.findById(systemId).orElseThrow(
() -&gt; new RuntimeException(&quot;Value Not found for class&quot; + SdlcSystem.class + &quot; and id: &quot; + systemId));
}
}

Restapiapplication.java

    @SpringBootApplication
public class RestapiApplication {
public static void main(String[] args) {
SpringApplication.run(RestapiApplication.class, args);
}
}

Error

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-09-12 19:35:17.256 ERROR 73258 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

APPLICATION FAILED TO START

Description:

Field sdlcService in com.restapi.restapi.Controller.ProjectRestController required a bean of type 'com.restapi.restapi.Service.SdlcService' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.restapi.restapi.Service.SdlcService' in your configuration.

答案1

得分: 1

你应该用 @Service 注解 SdlcServiceImpl(而不是它的接口)。

@Service javadoc 中可以看到:
> 表示被注解的 是一个 "Service"(…)
>
> 这个注解作为 @Component 的一个特化,允许通过类路径扫描自动检测 实现类

英文:

You should annotate SdlcServiceImpl (and not it's interface) with @Service.

From @Service javadoc:
>Indicates that an annotated class is a "Service" (...)
>
>This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

huangapple
  • 本文由 发表于 2020年9月12日 22:22:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63861297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定