I am using Spring Boot and Lombock, and I have a bean that is initialized with some String properties, and provides them to other classes:
@Getter
@Configuration
@PropertySource(value = "classpath:texts.properties")
public class TextProvider {
@Value("${some.text.value}")
private String text1;
@Value("${other.text.value}")
private String text2;
}
When Lombok creates the getters for this class, it copies the @Value annotation to the get methods, causing Spring's AutowiredAnnotationBeanPostProcessor to print the following info on system startup: "Autowired annotation should only be used on methods with parameters: " method.
Is there a way to not copy these annotations to the getter?
CodePudding user response:
I would always suggest to not use the @Value annotation for retrieving the values from property files. Use a property class for that:
@ConfigurationProperties(...)
@Getter
public class TextProperties {
private String text1;
private String text2;
}
Now read that in your configuration class:
@Configuration
@PropertySource(value = "classpath:texts.properties")
@EnableConfigurationProperties(TextProperties.class)
public class TextProvider {
...
}
That way, you can autowire the TextProperties everywhere you need it:
@Autowired
private TextProperties textProperties
Read here for some more information, especially on how to configure the @ConfigurationProperties annotation and how to name your properties.
CodePudding user response:
Why Don't you use @Value annotation in the All Args Constructor?
Like
@Getter
@Configuration
@PropertySource(value = "classpath:texts.properties")
public class TextProvider {
private String text1;
private String text2;
public TextProvider(@Value("${some.text.value}") String text1,@Value("${other.text.value}") String text2){
this.text1 = text1;
this.text2 = text2;
}
}
This way spring is happy and you can still use the @Getter Annotation of Lombok.
CodePudding user response:
By default, Lombok will not create a method of one has already been coded, so you could simply write your own getter.
The downside is that Lombok will generate a warning in this case, so it is best to actually tell Lombok to not even think about it by specifying AccessLevel.NONE, so :
@Getter
@Configuration
@PropertySource(value = "classpath:texts.properties")
public class TextProvider {
@Value("${some.text.value}")
@Getter(AccessLevel.NONE)
private String text1;
@Value("${other.text.value}")
@Getter(AccessLevel.NONE)
private String text2;
public String getText1()
{
return text1;
}
public String getText2()
{
return text2;
}
}
Of course, strictly for this example, that makes using @Getter at the class level totally useless - but this would be the approach for the general case of a class with many properties.
