2014-10-01 97 views
26

Spring Boot的@ConfigurationProperties注释有可能具有不可变(最终)字段吗?下面的例子不可变@ConfigurationProperties

@ConfigurationProperties(prefix = "example") 
public final class MyProps { 

    private final String neededProperty; 

    public MyProps(String neededProperty) { 
    this.neededProperty = neededProperty; 
    } 

    public String getNeededProperty() { .. } 
} 

途径我试过到目前为止:

  1. 创建MyProps类的@Bean有两个构造
    • 提供了两个构造函数:空与neededProperty参数
    • 的豆是用new MyProps()创建的
    • 在该领域的结果是null
  2. 使用@ComponentScan@Component提供MyProps豆。
    • 结果BeanInstantiationException - >NoSuchMethodException: MyProps.<init>()

我有它的工作的唯一方法是通过为每个非最终场提供的getter/setter。

+1

据我所知,你是什么试图做的事情不会开箱即用。 – geoand 2014-10-01 10:17:31

+0

很伤心。当然,我总是可以通过使用带'@ Value'注解的构造函数参数来实现纯Spring。但是,如果Spring Boot也支持这一点,那就太好了。 – RJo 2014-10-01 11:05:33

+0

我在源代码上花了一个小小的高峰,但它并不平凡,以支持你所要求的东西。当然,我不是Spring内部专家,所以我可能会错过一些明显的东西 – geoand 2014-10-01 12:22:52

回答

10

我必须经常解决这个问题,我使用了一点不同的方法,它允许我在一个类中使用final变量。

首先,我将所有的配置保存在一个地方(类),比如说叫做ApplicationProperties。该课程具有@ConfigurationProperties带特定前缀的注释。它也列在@EnableConfigurationProperties针对配置类(或主类)的注释中。

然后,我提供我的ApplicationProperties作为构造函数参数,并在构造函数中执行对final字段的赋值。

实施例:

主要类:

@SpringBootApplication 
@EnableConfigurationProperties(ApplicationProperties.class) 
public class Application { 
    public static void main(String... args) throws Exception { 
     SpringApplication.run(Application.class, args); 
    } 
} 

ApplicationProperties

@ConfigurationProperties(prefix = "myapp") 
public class ApplicationProperties { 

    private String someProperty; 

    // ... other properties and getters 

    public String getSomeProperty() { 
     return someProperty; 
    } 
} 

并与一类的最终性质

@Service 
public class SomeImplementation implements SomeInterface { 
    private final String someProperty; 

    @Autowired 
    public SomeImplementation(ApplicationProperties properties) { 
     this.someProperty = properties.getSomeProperty(); 
    } 

    // ... other methods/properties 
} 

我更喜欢这种方法的原因有很多,例如如果我必须在构造函数中设置更多的属性,我的构造函数参数列表并不“庞大”,因为我总是有一个参数(我的案例中为ApplicationProperties);如果有必要增加更多final性质,我的构造保持不变(只有一个参数) - 这可能会降低其他地方变化的号码等

我希望这将有助于

+1

这是很多的锅炉板与只使用@Value – 2016-11-09 19:56:33

+0

这是[tag:Java]。更多的样板意味着更好的代码 – Clijsters 2018-02-06 14:55:37

+0

@Clijsters我真的不知道你是否有点滔滔不绝,但我的意思是,它不太对,但它也不远! – 2018-02-12 00:34:57