16.9.2020 |

Spring Dependency Injection

Dependency Injection

Autowired

@Service
public class SendWelcomeMail {

    @Autowired
    private MailService mailService;

    ...

}
  • Works like magic
  • Has to much magic for Testing
  • Autowiring mode byType ->

Constructor Argument Resolution

@Service
@RequiredArgsConstructor
public class SendWelcomeMail {

    private final MailService mailService;

    ...

}

How about Configuration Properties?

Value

application.properties

mail.batchSize=10
@Service
public class SendWelcomeMail {

    @Value("${mail.batchSize}")
    private int batchSize;

    ...

}
  • No type safety
  • No fun to test like @Autowired

@Bean

Build the Bean yourself as part of a @Configuration.

@Configuration
@ConfigurationProperties(prefix = "mail")
public class MailConfiguration {

    private int batchSize;

    @Bean
    public SendWelcomeMail build() {
        return new SendWelcomeMail(batchSize);
    }
}

@Service
@RequiredArgsConstructor
public class SendWelcomeMail {

    private final int batchSize;

    ...

}
    • Type safety
    • Manual work
    • Dependency where a Configuration cares about who uses it

@value with Spring SpEL Bean

Flip the relation an let the Service say what configuration it needs and Spring will do the rest.

@Configuration
@ConfigurationProperties(prefix = "mail")
public class MailConfiguration {

    private int batchSize
}

@Service
@RequiredArgsConstructor
public class SendWelcomeMail {

    @Value("#{mailConfiguration.batchSize}")
    private final int batchSize;

    ...

}
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value
Zur Übersicht

Mehr vom DevSquad...

Jan Sauer

Wie Birdy uns hilft keine Geburtstage zu verpassen

Adrian Görisch

Column Layout in Css