When and how to use @Value Spring Boot?

Asked

Viewed 19 times

-1

Hello! I am doing the validation of vulnerabilities pointed out by Sonarqube in an API, and Sonar presented the following problem for the variables and objects:

inserir a descrição da imagem aqui

With the following suggestion for these excerpts: inserir a descrição da imagem aqui Also, what is the correct notation to use? I am using @Value, but to no avail.

1 answer

0


Each of these annotations has a different function, for example @Autowired is used by spring to create and inject instances of classes you have noted with @Service, @Component, @Repository or @Bean. That is, you don’t need to give new in class, spring will do it for you.

About @Value, it serves so that you can capture the value of some property defined there in that application.properties file in the Resources directory.

For example, if your application.properties is like this:

db.senha-do-bd=12345

You can capture the value in a variable

@Value("${db.senha-do-bd}")
private String senha;

here is a more complete tutorial: https://www.baeldung.com/spring-value-annotation

but overall, only with this chunk of code you can’t know what’s really going on, you need to understand what each note does and what your code is doing.

If you want to add more details to the question, we can help you better.

Edit: Maybe you can just delete this Provider variable if it is not being used.

  • An excellent explanation Israel, I updated the question with a larger passage, perhaps facilitate in understanding. In case all variables that are being used Sonar asks for a notation, I just could not identify which.

  • Could you add some code as well? To know what context these variables are in. If you click there on "Why is this an Issue?" can be useful too, usually it explains to you why you made this note

  • In this case, the chunk of codes are used within the methods... but there are many it is even impracticable to put them here... but in reality I just did not understand why it is necessary to have these notations in variables that are being used..

  • I imagine you should use the @Autowired, but you need to check if the class is a bean or spring Component. For example, if within the Closeablehttpclient class you have the annotation @Service, @Component, @Bean above, you can use the @Autowired and an instant will be automatically injected into you.

  • indicate the reading: https://blog.algaworks.com/injecao-de-dependencias-spring/

  • These classes are mostly Entitys... so I’m lost hehe... Thanks for the reading tip, I’ll read.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.