所以我正在做一个使用 spring 的项目 我正在尝试使用 propreties.yml 文件定义一个字符串值 使用 @Value("${sthg.sthg}") 这是它的图像
@Service
@Transactional
@Slf4j
@AllArgsConstructor
public class GedAuthenticationServiceImpl implements GedAuthenticationService {
@Value("${app.alfresco.alfresco_urls.alfresco_login_url}")
private final String authUrl;
我得到这个错误
Parameter 0 of constructor in package.class required a bean of type 'java.lang.String' that could not be found.
如果我像这样使用普通构造函数
@Service
@Transactional
@Slf4j
public class GedAuthenticationServiceImpl implements GedAuthenticationService {
private final String authUrl;
public GedAuthenticationServiceImpl( @Value("${app.alfresco.alfresco_urls.alfresco_login_url}") String authUrl) {
this.authUrl = authUrl;
}
它只是finneee
正如我所说,我使用了普通的构造函数,但我不知道为什么它不能与另一个构造函数一起使用 而且我似乎无法区分太多案例
通过使用
@AllArgsConstructor
,您在后台使用了 构造函数注入,默认情况下,当您的 Spring 组件类中只有一个构造函数时,它将使用 DI。
我的意思是说 Lombok 写了一个类似这样的代码:
public YourSeviceClass(String test) {
this.test = test;
}
在您的示例中,您的应用程序中没有声明
String
bean,因此 Spring 容器无法注入它。
创建一个单独的配置类,其中包含您的登录配置。不要在你的服务类中混合所有东西,这会让你的代码变得非常丑陋,并且 hard to read in future.
示例(如果您使用的是 Java 17,则使用记录):
@ConfigurationProperties(prefix = "app.alfresco...ect")
public class PropertyConfig {
private String myVariableName;
...
}
查看更多详细信息:https://www.baeldung.com/configuration-properties-in-spring-boot
我觉得你在spring boot的bean类中使用,相当于调用spring帮你注入一个名为
authUrl
的bean对象,它的类型是java.lang.String
。很明显,你没有用authUrl
定义一个bean对象,所以报错了
如果真的需要用
@AllArgsConstructor
给类成员赋值,建议用@RequiredArgsConstructor
代替,同时对需要构造的成员变量使用final修饰。其他的,例如您示例中的authUrl
,不需要使用最终修改。
希望对你有帮助,祝你好运
因为
lombok
不知道如何处理字段声明上的 @Value
注释,它什么都不做并创建构造函数,如:
public GedAuthenticationServiceImpl(String authUrl) {
this.authUrl = authUrl;
}
反过来导致
spring
失败,因为现在 spring
不知道如何处理该构造函数。在 lombok
方面,可能要求它复制字段注释到构造函数参数 - 请检查 lombok.copyableAnnotations
配置密钥,但是,我建议注意 @iLyas suggestion 并开始使用 @ConfigurationProperties
.