Quantcast
Channel: SpringBoot application doesn't autowire field - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by g00glen00b for SpringBoot application doesn't autowire field

$
0
0

You're using two bean declaration mechanisms:

  1. You're registering your bean using @Service
  2. You're registering a bean using @Bean

This means that your service will be created twice. The one defined using @Bean works properly, since it uses the @Value annotation to inject the proper value in your service.

However, the service created due to @Service doesn't know about the @Value annotation and will try to find any bean of type String, which it can't find, and thus it will throw the exception you're seeing.

Now, the solution is to pick either one of these. If you want to keep the @Bean configuration, you should remove the @Service annotation from ServiceAImpl and that will do the trick.


Alternatively, if you want to keep the @Service annotation, you should remove the @Bean declaration, and you should write your own constructor rather than relying on Lombok because this allows you to use the @Value annotation within the constructor:

@Service
public class ServiceAImpl implements ServiceA {
    private final String fieldA;

    /**
     * This constructor works as well
     */
    public ServiceAImpl(@Value("${fieldA}") String fieldA) {
        this.fieldA = fieldA;
    }

    @Override 
    public boolean isFieldA(String text){
        return fieldA.equals(text);
    }
}

Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>