【问题标题】:@Value property injection not working in GenericFilterBean Spring@Value 属性注入在 GenericFilterBean Spring 中不起作用
【发布时间】:2017-10-10 13:46:03
【问题描述】:

我正在尝试从属性文件中注入属性。我正在使用 Spring 4.3 版本。 属性文件位于 src/main/resources 文件夹中。

在 Web.xml 中,我有以下过滤器配置

<filter>
    <filter-name>securityFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>securityFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

我的自定义过滤器类:

public class SecurityFilter extends GenericFilterBean {

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

     ...         

     }   

在 Spring Application 上下文 XML 文件中:

<context:property-placeholder location="classpath*:authentication.properties"/>
<bean id="securityFilter" class="com.example.SecurityFilter"/>

但是在启动服务器时会抛出无法创建 bean 的异常

Error creating bean with name 'securityFilter': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: 
Could not resolve placeholder 'url.value' in string value "${url.value}"

【问题讨论】:

    标签: spring filter servlet-filters


    【解决方案1】:

    您的代码有一半使用注释,一半使用 XML。尝试完全使用注释。用@Component 标记该类,并确保它的包包含在您的应用程序servlet 文件的上下文组件扫描器中。确保属性文件具有所需的条目,并且您无需显式编写 bean。 更新: 确保类路径中有属性文件。

    【讨论】:

    • 您好 Jajikanth,感谢您的回复。我尝试使用 @Component 注释对类进行注释,但它仍然会引发相同的错误。它无法将属性映射到字符串。无法解析字符串值“${url.value}”中的占位符“url”
    • 一种可能是您的属性文件未包含在类路径中。你确定吗?请分享您的项目结构的屏幕截图。我在下面的链接中的回答可能会提供更多的想法。但它不使用注释。stackoverflow.com/questions/43710016/…
    • @Jaijikanth 你是对的。属性文件不在类路径中。现在问题已经解决,我可以加载属性文件了。
    猜你喜欢
    • 2011-08-06
    • 2022-06-22
    • 2016-06-05
    • 2011-09-19
    • 1970-01-01
    • 2011-10-31
    • 2021-03-31
    • 2018-02-12
    • 2018-03-03
    相关资源
    最近更新 更多