在Spring Boot 2.2.4中如何与@ConfigurationProperties一起使用@ConstructorBinding和@PropertySource?

时间:2020-02-25 11:12:37

标签: java spring spring-boot immutability

我是Spring Boot的新手。目前,我正在尝试创建一个POJO类( SystemProperties.class )以读取属性文件( parameter.properties )中与应用程序.properties分开的值,但仍位于相同的目录/ src / main / resources。当我在类中使用@ConstructorBinding使其不可变时,就会发生此问题。

  • @ConstructorBinding需要与@EnableConfigurationProperties或@ConfigurationPropertiesScan一起使用。
  • @ConfigurationPropertiesScan将忽略使用@PropertySource指定外部时所需的@Configuration批注
    * .properties文件。

A)SystemProperties.class

var express=require ('express');
const cors=require('cors');
var app = express();
const bodyParser=require('body-parser');
const http=require('http');
const port=5000;

var corsOptions =
{
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200,
    allowHeaders: ['sessionId', 'Content-Type'],
    exposedHeaders: ['sessionId'],
    credentials: true,
}
app.use(cors(corsOptions));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
const server= http.createServer(app)
//-------------------------- Pulling Networks----------//
 let net= `SELECT networks.*, products.product FROM products JOIN networks ON 
  products.id=networks.product_Id`;
        con.query(net, function(err, result, fields) {
            if (err) throw err;
            let stringifiedJson = JSON.stringify(result)
            let  networksArr= JSON.parse(stringifiedJson)
    res.send(networksArr);
//-------------------------- Pulling Networks----------//

 //Connection to port 5000
    server.listen(port, function () {
    console.log('New program 25.2!!');
  })

B)parameter.properties

@Configuration
@PropertySource("classpath:parameter.properties")

@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {

    private final String test;

    public SystemProperties (
            String test) {
        this.test = test;
    }

    public String getTest() {
        return test;
    }

我尝试删除@PropertySource批注,但是除非从application.properties中获取,否则无法检索该值。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

解决此问题的方法是将类分为两个具有两个不同关注点的类。使用这种解决方案,您可以保留创建的SystemProperties类,并另外添加一个仅用于加载属性文件参数的类,以使它们可用于您的应用程序。

解决方案如下:

@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {

    private final String test;

    public SystemProperties(
            String test) {
        this.test = test;
    }

    public String getTest() {
        return test;
    }
}

请注意,我已经省略了@Configuration@PropertySource注释。

@Configuration
@PropertySource("classpath:parameter.properties")
public class PropertySourceLoader {
}

注意,我只是将此注释添加到了一个新类中,该类是专门为加载属性文件而创建的。

最后,您可以在主应用程序类上添加@ConfigurationPropertiesScan以启用属性映射机制。