gpt4 book ai didi

java - lombok @RequiredArgsConstructor 如何向构造函数 spring boot 注入(inject)值

转载 作者:行者123 更新时间:2023-12-04 13:55:25 29 4
gpt4 key购买 nike

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

@RequiredArgsConstructor
@Service
public class Test{

private final String str;
private String str5;

// more code

}
在非 Spring 引导中,我们在 xml 中提供:
<bean id="Test" class="com.abc.Test">
<constructor-arg index="0" value="${xyz}"/>
</bean>
如何从 spring boot 实现相同的可能是通过 application.properties 但如何注入(inject)

最佳答案

@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)

关于java - lombok @RequiredArgsConstructor 如何向构造函数 spring boot 注入(inject)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63380477/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com