SpEL Bean引用

Bean的引用

声明

首先这个系列的本篇博客参照油管Spring Expression Language教学视频Referencing Beans而写。

开始

这集就是简单的看看怎么使用spEL来引用Bean

  • All Spring Expresions should be declared inside ${...} or #{...}
  • Any bean can be directly accessed using the id attribute of the bean.

2点应该很容易理解,我们来聊聊第1点吧。百度了一下几乎没有说这个的,所以Google🌏了一下,Spring Expression Language (SpEL) with @Value: dollar vs. hash ($ vs. #)中的高赞回答解释的非常清晰

${...} is the property placeholder syntax. It can only be used to dereference properties.

#{...} is SpEL syntax, which is far more capable and complex. It can also handle property placeholders, and a lot more besides.

Both are valid, and neither is deprecated.

#{...}非常强大可以做spEL的任何事情,而${...}则用于获得property值得注意的是这里propertyproperty配置文件里的property

Use ${key_name} To Read Property Value In Properties File.

  1. Get the value of the specified key in the external properties file.
  2. Can be used in XML configuration file or in java file with @Value annotation.
  3. Get spring-context environment variables in pom.xml properties definition.

更详细的区别和应用可继续阅读该博客Spring Expression Language Example $ vs #

首先创建几个类

Book

public class Book {
   
    private int bookId;
    private String bookName;

    public int getBookId() {
   
        return bookId;
    }

    public void setBookId(int bookId) {
   
        this.bookId = bookId;
    }

    public String getBookName() {
   
        return bookName;
    }

    public void setBookName(String bookName) {
   
        this.bookName = bookName;
    }
}

BookCollection

import java.util.List;

public class BookCollection {
   
    private List<Book> bookList;

    public List<<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中,可以使用SpEL表达式绑定方法参数。具体步骤如下: 1. 在方法参数上添加@org.springframework.web.bind.annotation.RequestParam注解(或其他适当的注解),并指定SpEL表达式作为其属性值。 2. 在方法上添加@org.springframework.web.bind.annotation.GetMapping(或其他适当的注解),并设置其value属性来指定请求的URL。 3. 在应用程序上下文中配置一个DefaultSpELExpressionParser bean。 4. 在方法参数上添加@org.springframework.beans.factory.annotation.Value注解,并使用SpEL表达式引用应用程序上下文中的bean。 例如,以下代码展示了如何在Spring MVC中使用SpEL表达式绑定方法参数: ```java @RestController public class MyController { @GetMapping("/user/{id}") public User getUserById(@PathVariable("id") int id, @RequestParam("#{systemProperties['user.language']}") String language, @Value("#{myService.someProperty}") String someProperty) { // ... } } ``` 在上面的代码中,getUserById方法使用@PathVariable注解将URL路径中的{id}绑定到方法参数id上。然后,它使用@RequestParam注解将请求参数language绑定到方法参数language上,这里的SpEL表达式#{systemProperties['user.language']}将系统属性user.language的值作为参数传递给方法。最后,它使用@Value注解将应用程序上下文中名为myService的bean的someProperty属性绑定到方法参数someProperty上,这里的SpEL表达式#{myService.someProperty}将该属性的值作为参数传递给方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值