UnsatisfiedDependencyException 尝试在 eclipse 中配置基本的 spring-boot 项目时

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

UnsatisfiedDependencyException trying to configure a basic spring-boot project in eclipse

问题

我正在尝试在Eclipse(带有STS)中配置一个基本的Spring Boot项目,我想在其中定义一个控制器类和一个实体类以在控制器中进行自动装配,但是我遇到了一个异常。我一直在努力修复它,但现在我没有想法了,有人可以帮助我吗?

一切都很正常(我可以在控制器中获取实体对象,并且HTTP请求"http://localhost:8080/index"以正确的方式返回我的视图)...... 直到我在"Entidad"类中定义一个构造函数,然后我就会收到异常。

以下是我的代码:

package com.example.springMVC_ejemplo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}
package com.example.springMVC_ejemplo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.springMVC_ejemplo.model.Entidad;

@Controller
public class MyController {

    List<Entidad> exampleEntityList = new ArrayList<>();

    // 通过application.properties进行注入
    @Value("${index.message}")
    private String message;

    @Autowired
    private Entidad entidad;

    @PostConstruct
    private void initExampleEntityList() {
        String nombre = entidad.getNombre();
        System.out.println("Initializing list of example entities");
    }

    @GetMapping(value= {"/", "/index"})
    public String main(Model model) {
        model.addAttribute("message", message);
        return "index";
    }

}
package com.example.springMVC_ejemplo.model;

import org.springframework.stereotype.Service;

@Service
public class Entidad {

    private String nombre;
    private String atributo1;
    private String atributo2;
    
    private Entidad(String nombre, String atributo1, String atributo2) {
        super();
        this.nombre = nombre;
        this.atributo1 = atributo1;
        this.atributo2 = atributo2;
    }
    
    public String getNombre() {
        return nombre;
    }
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    public String getAtributo1() {
        return atributo1;
    }
    public void setAtributo1(String atributo1) {
        this.atributo1 = atributo1;
    }
    public String getAtributo2() {
        return atributo2;
    }
    public void setAtributo2(String atributo2) {
        this.atributo2 = atributo2;
    }
    
}

我得到的异常信息如下:

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

2020-04-07 20:26:57.072  INFO 18236 --- [           main] c.e.s.SpringMvcBahiaProjectApplication   : Starting SpringMvcBahiaProjectApplication on DESKTOP-40IFSQT with PID 18236 (C:\Users\ignac\OneDrive\Documentos\eclipse-workspace\springMVC_BahiaProject\target\classes started by ignac in C:\Users\ignac\OneDrive\Documentos\eclipse-workspace\springMVC_BahiaProject)
...

错误信息的关键部分如下:

Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate.

请注意,我只翻译了你提供的代码和异常部分,不包括额外的内容。如果需要进一步帮助,请随时提问。

英文:

I'm trying to configure in eclipse (with STS) a basic spring-boot project where I want to define a controller class and an entity class to autowired in controller, but I'm getting an exception. I've been trying to fix it but now I'm without ideas,can someone help me?

All works fine (I can get an entity object in my controller and the http request "http://localhost:8080/index" return my view in a correct way)... until I define a construct in the "Entidad" class and I get the exception.

here my code:

package com.example.springMVC_ejemplo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}

package com.example.springMVC_ejemplo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.springMVC_ejemplo.model.Entidad;

@Controller
public class MyController {

	List&lt;Entidad&gt; exampleEntityList = new ArrayList&lt;&gt;();
	
    // inject via application.properties
    @Value(&quot;${index.message}&quot;)
    private String message;

    @Autowired
    private Entidad entidad;
    
    @PostConstruct
    private void initExampleEntityList() {
        String nombre = entidad.getNombre();
    	System.out.println(&quot;Inicializando la lista de entidades de ejemplo&quot;);
    }
    
    @GetMapping(value= {&quot;/&quot;,&quot;/index&quot;})
    public String main(Model model) {
        model.addAttribute(&quot;message&quot;, message);
        return &quot;index&quot;;
    }
    
}

package com.example.springMVC_ejemplo.model;

import org.springframework.stereotype.Service;

@Service
public class Entidad {

	private String nombre;
	private String atributo1;
	private String atributo2;
	
	private Entidad(String nombre, String atributo1, String atributo2) {
		super();
		this.nombre = nombre;
		this.atributo1 = atributo1;
		this.atributo2 = atributo2;
	}
	
	public String getNombre() {
		return nombre;
	}
	public void setNombre(String nombre) {
		this.nombre = nombre;
	}
	public String getAtributo1() {
		return atributo1;
	}
	public void setAtributo1(String atributo1) {
		this.atributo1 = atributo1;
	}
	public String getAtributo2() {
		return atributo2;
	}
	public void setAtributo2(String atributo2) {
		this.atributo2 = atributo2;
	}
	
}

And the exception I get is:

  .   ____          _            __ _ _
 /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  &#39;  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.6.RELEASE)

2020-04-07 20:26:57.072  INFO 18236 --- [           main] c.e.s.SpringMvcBahiaProjectApplication   : Starting SpringMvcBahiaProjectApplication on DESKTOP-40IFSQT with PID 18236 (C:\Users\ignac\OneDrive\Documentos\eclipse-workspace\springMVC_BahiaProject\target\classes started by ignac in C:\Users\ignac\OneDrive\Documentos\eclipse-workspace\springMVC_BahiaProject)
2020-04-07 20:26:57.075  INFO 18236 --- [           main] c.e.s.SpringMvcBahiaProjectApplication   : No active profile set, falling back to default profiles: default
2020-04-07 20:26:57.682  INFO 18236 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-04-07 20:26:57.689  INFO 18236 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-04-07 20:26:57.689  INFO 18236 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.33]
2020-04-07 20:26:57.742  INFO 18236 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-04-07 20:26:57.743  INFO 18236 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 639 ms
2020-04-07 20:26:57.777  WARN 18236 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;myController&#39;: Unsatisfied dependency expressed through field &#39;entidad&#39;; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;entidad&#39; defined in file [C:\Users\ignac\OneDrive\Documentos\eclipse-workspace\springMVC_BahiaProject\target\classes\com\example\springMVC_ejemplo\model\Entidad.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type &#39;java.lang.String&#39; available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-04-07 20:26:57.779  INFO 18236 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-04-07 20:26:57.787  INFO 18236 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with &#39;debug&#39; enabled.
2020-04-07 20:26:57.870 ERROR 18236 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Parameter 0 of constructor in com.example.springMVC_ejemplo.model.Entidad required a bean of type &#39;java.lang.String&#39; 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 &#39;java.lang.String&#39; in your configuration.

Thanks in advance!

答案1

得分: 1

你的 Entidad 不应该是一个 @Service。(你会得到异常,因为 Spring 不知道要传递哪些字符串到构造函数)

移除这个注解,也不要将它注入到你的 @Controller 中。毕竟它只是一个简单的模型对象。

英文:

Your Entidad should not be a @Service. (You get the exception because Spring doesn't know which Strings to pass into the constructor)

Remove the annotation and do not @Autowire it into your @Controller. It is a simple model object, after all.

答案2

得分: 1

  1. 从Entidad bean类中移除@Service。
  2. 向Entidad类添加无参构造函数,否则Spring容器将无法实例化Entidad类,或者移除@Autowire。
英文:
  1. Remove @Service from Entidad bean class.
  2. Add no argument constructor to Entidad class, Otherwise spring container will not be able to instantiate Entidad class or remove @Autowire.

huangapple
  • 本文由 发表于 2020年4月8日 02:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61087310.html
匿名

发表评论

匿名网友

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

确定