![](/img/trans.png)
[英]How do I inject a value from Properties file to a field of an existing instance (not managed by Spring) using Spring annotations?
[英]Java Spring properties inject @Value instance Null
我有一个 class 来加载属性,但是当我创建一个实例时,class 总是 null。
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Blacklist
{
@Getter
@Value("${blacklist.regex:}")
public String regex;
}
实例
public class Filter{
private BlackList blacklist = new BlackList();
private regex = blackList.getRegex();
}
黑名单是 null
我尝试使用@autowired,但它不起作用。 特性:
blacklist.regex=^.{1,50}$
我认为这里有多个问题。
我的建议:
我发现了问题,我的 class 过滤器没有 Spring 逻辑来注入值,我将使用 Bean 配置器和构造器。
@Value("${blacklist.regex:}")
public String regex;
@Bean
public Filter()
{
return new Filter(regex);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.