有没有更好的方法将变量传递到视图层而不是使用控制器?

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

每次创建控制器路由时,我都必须将变量传递给视图层:

@Configuration
public class Config {

    @Value("${api.url}")
    private String apiUrl;

    @Bean
    public String API_URL() {
        return apiUrl;
    }

}

@Controller
public class ClientController {

    @Autowired
    private String API_URL;
        
    @GetMapping("/clients")
    public String viewListe(Model model) {
        model.addAttribute("API_URL", API_URL); // here is the passing of the variable to the view layer
        return "client/client-list";
    }
}

这很乏味。所以我想知道是否有更好的方法来传递这个变量;例如是否可以在

@SpringBootApplication
部分传递它?

@SpringBootApplication
public class BackendApplication {
    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }
}
spring-boot thymeleaf
1个回答
0
投票

可以访问 Thymeleaf 视图中的 bean。因此,在您的情况下,无需将

API_URL
作为属性传递给每个模型,只需访问如下字符串:
${@API_URL}

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