lombok @RequiredArgsConstructor如何将值注入构造函数spring boot

问题描述

我有一个带有lombok @requiredArgsConstructor的类:

/api/

在非春季启动中,我们以xml格式提供:

@requiredArgsConstructor
@Service
public class Test{

private final String str;
private String str5;

// more code

}

如何通过spring boot实现相同的功能可能是通过application.properties,但是如何注入

解决方法

需要删除@Service批注,并且必须在带有@Configuration注释方法的@Bean类中创建该bean,并返回该类类型。

//Test.java
package com.abc;

import lombok.RequiredArgsConstructor;
import lombok.ToString;

@RequiredArgsConstructor
@ToString
public class Test {

private final String str;
private String str5;

}
//DemoApplication.java
package com.abc;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }

    @Bean
    Test buildTest(@Value("${xyz}") String value) {
        return new Test(value);
    }

}

注意:@SpringBootApplication暗示@Configuration

//DemoApplicationTests.java
package com.abc;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    com.abc.Test test;

    @Test
    void contextLoads() {
        System.out.println(test);
    }

}
#application.properties
xyz=print me

结果:

Test(str=print me,str5=null)
,

在这种情况下,我认为您最好对字段进行注释:

@Service
public class Test{

    @Value("${xyz}")
    private String str;

    private String str5;

    // more code
}

或使用带注释的参数显式定义构造函数:

@Service
public class Test{

    private final String str;

    private String str5;

    public Test(@Value("${xyz}") String str) {
        this.str = str;
    }
    // more code
}

如果还有其他 final 字段,则可以将lombok构造函数生成与字段注释结合起来,如Best practice for @Value fields,Lombok,and Constructor Injection?

中所述
@RequiredArgsConstructor
@Service
public class Test{

    @Value("${xyz}")
    private String str;

    private final String str5;

    // more code
}