Skip to content
Advertisement

Spring Boot application.properties custom variable in a non-controller class

How come application.properties will work in a RestController, but not in a service class?

//application.properties
test=test

Works Perfect!

@RestController
public class invitecontroller {

    @Autowired inviteconfig inviteconfig;
    
    @PostMapping("/v1/invite")
    public void invite(@RequestBody XXX XXX) {

        System.out.println(inviteconfig);

    }
}

Returns “Null”

@Service
public class inviteservice {
    
    @Autowired inviteconfig inviteconfig;

    public void invite() {
       System.out.println(inviteconfig);
    }
}
@Configuration
@Data
public class inviteconfig {
    private String test;
}

Advertisement

Answer

The inviteservice class is not configured for Spring IoC (Inversion of Control) as a bean, so Spring will not handle the inviteservice class lifecycle. In this case, @Autowired is useless.

To fix this try to add @Component annotation to invitesevice, to declare it as a component:

@Component
public class inviteservice {
    
    @Autowired inviteconfig inviteconfig;

    public void invite() {
       System.out.println(inviteconfig);
    }
}

In the case of the controller, with @RestController, Spring will recognize your class as a Spring component.

Finally, don’t forget to inject inviteservice using Spring IoC (using @Autowired annotation, or other means)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement