@ConfigurationProperties前缀不起作用一般答案

2022-09-01 00:26:33

.yml 文件

cassandra:
    keyspaceApp:junit
solr:
    keyspaceApp:xyz

@Component
@ConfigurationProperties(prefix="cassandra")
public class CassandraClientNew {
   @Value("${keyspaceApp:@null}") private String keyspaceApp;

主方法文件

@EnableAutoConfiguration
@ComponentScan
@PropertySource("application.yml")
public class CommonDataApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(CommonDataApplication.class)
                .web(false).headless(true).main(CommonDataApplication.class).run(args);
    }
}

测试用例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CommonDataApplication.class)
@IntegrationTest
@EnableConfigurationProperties
public class CassandraClientTest {

    @Autowired
    CassandraClientNew cassandraClientNew;

    @Test
    public void test(){
        cassandraClientNew.getSession();
        System.out.println(" **** done ****");
    }
}

它不是将 junit 设置为 keyspaceApp,而是设置 xyz。

看起来像前缀=“cassandra”不起作用


答案 1

看起来您正在尝试使用弹簧引导类型安全配置属性功能。

因此,为了让它正常工作,您必须对代码进行一些更改:

首先,你的类应该有注释,例如:CommonDataApplication@EnableConfigurationProperties

@EnableAutoConfiguration
@ComponentScan
@PropertySource("application.yml")
@EnableConfigurationProperties
public class CommonDataApplication {

    public static void main(String[] args) {
        // ...
    }
}

我不认为你需要注释,因为(以及和)是Spring Boot使用的默认配置文件。@PropertySource("application.yml")application.ymlapplication.propertiesapplication.xml

您的类不需要具有批注前缀属性。你必须有一个设定方法CassandraClientNew@ValuekeyspaceAppkeyspaceApp

@Component
@ConfigurationProperties(prefix="cassandra")
public class CassandraClientNew {

   private String keyspaceApp;

   public void setKeyspaceApp(final String keyspaceApp) {
       this.keyspaceApp = keyspaceApp;
   }
}

顺便说一句,如果您使用的是 或 s 并且初始化了集合(例如 ),则只需要 getter。如果集合未初始化,则还需要提供 setter 方法(否则将引发异常)。ListSetList<String> values = new ArrayList<>();

我希望这会有所帮助。


答案 2

一般答案

1. 在属性文件中(application.properties 或 application.yml)

# In application.yaml
a:
  b:
    c: some_string

2. 声明您的类:

@Component
@ConfigurationProperties(prefix = "a", ignoreUnknownFiels = false)
public class MyClassA {

  public MyClassB theB;   // This name actually does not mean anything
                          // It can be anything      
  public void setTheB(MyClassB theB) {
    this.theB = theB;
  }

  public static MyClassB {

    public String theC;

    public void setTheC(String theC) {
      this.theC = theC;
    }

  }

}

3. 宣布公开发起人!这是至关重要的!

请确保在上面的类中声明这些公共方法。确保它们具有“公共”修饰符。

// In MyClassA
public void setTheB(MyClassB theB) {
  this.theB = theB;
}

// In MyClassB
public void setTheC(String theC) {
  this.theC = theC;
}

就是这样。

结语

  • 类中的属性名称对 Spring 没有任何意义。它只使用公共设置器。我宣布他们是公开的,而不是在这里宣布公开的。您的属性可能具有任何访问修饰符。
  • 注意属性“忽略未知字段”。其默认值为“true”。当它是“false”时,如果文件“application.yml”中的任何属性未绑定到任何类属性,它将引发异常。它将在调试期间为您提供很多帮助。

推荐