忽略Spring依赖库的@Value字段处理

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

我将一个项目用作另一个项目的依赖项。依赖项目中的类之一如下:

public class Dependency {

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

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

  public Dependency() {

  }

  public Dependency(String xyz, String abc) {
    this.xyz = xyz;
    this.abc = abc;
  }
}

我试图在启动时在另一个项目中创建Dependency的实例,如下所示:

@Configuration
@PropertySource(value = {
    "classpath:appEnv.properties"
}, ignoreResourceNotFound = true)

public class Test {

  @Bean(name = "dependencyBean")
  public Dependent getDependent() {
    return new Dependent("xyz", "abc");
  }
}

我收到以下异常

BeanCreationException:创建名称为'DependentBean'的bean时出错:自动连接依赖项的注入失败;嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动连线字段:private java.lang.String xyz;

[如何在不调用试图解析带有postProcessPropertyValues批注的字段的@Value的情况下创建依赖类的实例?是因为我是在Spring容器中创建bean而被调用的吗?

java spring-boot spring-annotations
1个回答
0
投票

您可以通过将属性PropertySourcesPlaceholderConfigurer设置为ignoreResourceNotFound来创建true bean

@Bean
public static PropertySourcesPlaceholderConfigurer 
propertySourcesPlaceholderConfigurer() {
   PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertySourcesPlaceholderConfigurer;
}

public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound)

如果找不到属性资源,则设置为忽略。

如果属性文件是完全可选的,则

“ true”是适当的。默认值为“ false”。

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