Springboot - @Autowired null in configuration file

Asked

Viewed 120 times

0

I’m starting a project with springboot and need to access some properties of application.properties because of the profiles.

But when I inject the configuration class, it always comes null, I’ve researched enough but there must be some detail that I’m not paying attention to...

I’ll put the excerpts of the classes below

Application properties:

server.ip=000.000.000.000
server.port=0000

Configuration class:

@Component
@ConfigurationProperties(prefix = "server")
public class AppProperties {

    private String ip;
    private Integer port;

... getters ans setters

Class where I need to use values:

@Component
public class Teste {

    @Autowired
    private AppProperties properties;

...

    socket = new Socket(properties.getIp(), properties.getPort());

On the last line, the properties variable is null.

I already debugged and when the application starts the values are populated correctly in the Appproperties class.

Someone can give me a light?

2 answers

0

In the AppProperties you should be using @Configuration instead of @Component. Your prefix configuration is right, I believe the problem is just the wrong Annotation.

  • Thank you for your reply. I had already tried with both notes. When I start the application and debug these variables they are with the correct values. It seems to me that by using dependency injection these values are being lost.

0

At one point I instantiated the Test class with new Teste(). That’s where the problem was. I injected a class dependency injection Teste in the service class where I will need to use it and everything worked correctly.

Browser other questions tagged

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