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

Tec*_*hno 7 java constructor-injection lombok spring-boot

我有一个带有 lombok @RequiredArgsConstructor 的课程:

@RequiredArgsConstructor
@Service
public class Test{

private final String str;
private String str5;

// more code

}
Run Code Online (Sandbox Code Playgroud)

在非 Spring Boot 中,我们在 xml 中提供如下:

<bean id="Test" class="com.abc.Test">
        <constructor-arg index="0" value="${xyz}"/>
    </bean>
Run Code Online (Sandbox Code Playgroud)

如何从 Spring Boot 实现相同的目标可能是通过 application.properties 但如何注入

Len*_*nry 0

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

//Test.java
package com.abc;

import lombok.RequiredArgsConstructor;
import lombok.ToString;

@RequiredArgsConstructor
@ToString
public class Test {

private final String str;
private String str5;

}
Run Code Online (Sandbox Code Playgroud)
//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);
    }

}

Run Code Online (Sandbox Code Playgroud)

注:@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);
    }

}
Run Code Online (Sandbox Code Playgroud)
#application.properties
xyz=print me
Run Code Online (Sandbox Code Playgroud)

结果:

Test(str=print me, str5=null)
Run Code Online (Sandbox Code Playgroud)