SpringBoot中如何将@value注解的值传递给控制器

问题描述 投票:0回答:2

我有一个 spring,其中使用以下依赖项: spring-boot-starter-web v-2.7.3、spring-boot-devtools 和 spring-boot-starter-thymeleaf 我的目的是发送一个“Invoice”类客户端类和 ItemFactura 类对控制器的依赖关系,使用 @value 注释,我添加了位于 application.properties 中的环境变量:

factura.descripcion: Deporte

我将它与 @value 添加到我的 java 发票类中:

@Component
public class Factura {

@Value("${factura.descripcion}")
private String descripcion;

@Autowired
private Cliente cliente; 

private List<ItemFactura> items; 

/**
 * @return String return the description
 */
public String getDescription() {
    return descripcion;
}

/**
 * @param descripcion the description to set
 */
public void setDescription(String descripcion) {
    this.descripcion = descripcion;
}

/**
 * @return Cliente return the cliente
 */
public Cliente getCliente() {
    return cliente;
}

/**
 * @param cliente the cliente to set
 */
public void setCliente(Cliente cliente) {
    this.cliente = cliente;
}

/**
 * @return List<ItemFactura> return the items
 */
public List<ItemFactura> getItems() {
    return items;
}

/**
 * @param items the items to set
 */
public void setItems(List<ItemFactura> items) {
    this.items = items;
}

}

Después de esto inyecto la clase Factura en el controlador:

@Controller
@RequestMapping("/Factura")
public class FacturaController {

@Autowired
private Factura factura; 

@GetMapping("/ver")
public String verFactura(Model model){
    model.addAttribute("factura", factura);
    model.addAttribute("Titulo_factura", "Esto es el título de una factura");

    return "index";
    
}

}

Y por último la llamó en mi index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facturas</title>
</head>
<body>
<h1>Aquí se ven las facturas</h1>

<h1 th:text="${Titulo_factura}"></h1>
<h1 th:text="${factura.descripcion}"></h1>



</body>
</html>

当我再次抬起并输入路线时,出现错误: Caused by: org.attoparser.ParseException: 评估 SpringEL 表达式的异常:“invoice.description”(模板:“ver-invoice” - 第 13 行,第 9 栏) **由以下原因引起:org.springframework.expression.spel.SpelEvaluationException:EL1008E:在“com.nodependencyinjection.demo.Domain.Factura”类型的对象上找不到属性或字段“描述” - 可能不是公开的或无效? **

我的首要反应是公开的私人描述,但为了实现对对象的封装,我选择了错误的选项 com.nodependencyinjection.demo.Domain.Factura 和 mi com。 nodependencyinjection.demo.Controllers 是不同的组件,可以在 application.properties 中使用特殊的配置变量,然后再进行配置。

pddt:当我仅在 html 中添加“factura”时,页面会正确加载,并且我会得到该类的哈希值。

这让我很困惑...

html image

java spring spring-boot
2个回答
0
投票
属性是

descripcion

 所以你需要一个 getter 
getDescripcion()
 而不是 
getDescription()

    


0
投票
@value 注释的值通过 application.properties 文件传递到控制器,并且值为 Static。

© www.soinside.com 2019 - 2024. All rights reserved.