如何通过类静态属性实现注入实例方法的spring应用?

更新于
2026-07-30 16:23:13
14阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计344个文字,预计阅读时间需要2分钟。

如何通过类静态属性实现注入实例方法的spring应用?

我们知道,在正常情况下,Spring中的一个Bean需要依赖其他资源,如properties文件或其他Bean。直接使用@Value或@Autowired注解即可实现依赖注入。这两个注解相当于在Spring+Application Context+xml文件定义Bean时,property节点的配置。

我们知道,正常情况下,spring的一个bean要依赖其他资源,如properties或其他bean,直接利用@Value或@Autowired就可以了。这两个注解就相当于spring application context xml文件定义bean时的property节点。相当于调用了每个属性的set方法。

<bean id="person" class="com.myapp.core.spel.xml.Person"> <property name="book" value="book" /> <property name="bookName" value="#{book.name}"/> </bean>

然而,当一个java类里的静态方法需要引用一个spring资源时,我们需要定义静态属性,然后通过显示声明它们的set方法(注意,这个set方法是非静态的哦),来实现静态属性的注入。

见如下示例代码,其中dingdingReceiverMan属性的set方法通过@Value注解来注入一个配置

“monitor_log.dingding.receiverMan”;redisUtil属性的set方法通过@Autowired注解来注入一个bean——被@Component修饰的类“RedisUtil”。

阅读全文

本文共计344个文字,预计阅读时间需要2分钟。

如何通过类静态属性实现注入实例方法的spring应用?

我们知道,在正常情况下,Spring中的一个Bean需要依赖其他资源,如properties文件或其他Bean。直接使用@Value或@Autowired注解即可实现依赖注入。这两个注解相当于在Spring+Application Context+xml文件定义Bean时,property节点的配置。

我们知道,正常情况下,spring的一个bean要依赖其他资源,如properties或其他bean,直接利用@Value或@Autowired就可以了。这两个注解就相当于spring application context xml文件定义bean时的property节点。相当于调用了每个属性的set方法。

<bean id="person" class="com.myapp.core.spel.xml.Person"> <property name="book" value="book" /> <property name="bookName" value="#{book.name}"/> </bean>

然而,当一个java类里的静态方法需要引用一个spring资源时,我们需要定义静态属性,然后通过显示声明它们的set方法(注意,这个set方法是非静态的哦),来实现静态属性的注入。

见如下示例代码,其中dingdingReceiverMan属性的set方法通过@Value注解来注入一个配置

“monitor_log.dingding.receiverMan”;redisUtil属性的set方法通过@Autowired注解来注入一个bean——被@Component修饰的类“RedisUtil”。

阅读全文