Injection de dépendance

Quelle annotation


@Configuration class SpinderMan {}
@Service class IronMan {}
@Controller class CaptainAmerica {}
@Repository class Wolverine {}
@Component class MisterFantastic {}

Singleton

Tout bean Spring est un singleton


@Service
@Scope("prototype") // -> pas singleton
class Ultron {}

@Configuration

  • Permet la « springification » d'objet via @Bean
  • lieu parfait pour mettre en place des constructions Rx

@Lazy

Tout bean dans "shared" devrait être @Lazy

@Lazy @Autowire


@Service
class Thor {
	private final Mjolnir mjolnir;

	@Autowire
	public Thor(@Lazy Mjolnir mjolnir) {
		this.mjolnir = mjolnir; // peut être null
	}
}

Attention

  • Spring utilise massivement le local thread storage ! C'est incompatible avec l'utilisation de reactive stream.
  • Utilisation de différentes annotations de méthodes au sein d'un même bean…

@Service
class CaptainAmerica {
    @Transaction
    public void handshake() {
        // du code
	}

    @PreAuthorize("true")
    public void hug() {
        // du code
    }
}

Astuces


@Service
class AntMan {
    private final Collection<Ant> ants;

    @Autowire
    public AntMan(Collection<Ant> ants) {
        this.ants = ants;
    }
}

Pour aller plus loin

Pour un tas de raison Spring va proxifier les classes avec Spring framework 5 + Spring Boot 2, il n'utilise plus que la méthode standard de création de proxy

Pour aller plus loin


interface InronMan {
    String blast();
}
// ailleurs
InronMan ironMan = (InronMan) Proxy.newProxyInstance(
    Thread.currentThread().getContextClassLoader(),
    new Class[] { InronMan.class },
    (proxy, method, args) -> "Tony Stark"
);
 
log.info("print => {}", ironMan.blast()); // affiche "print => biz"

Tests


class MyTest {
    @Test
    public void test() {
        // GIVEN
        ConfigurationManager.getConfigInstance()
            .setProperty("BlackPanther", "T'Challa");

        // WHEN
        String myVar = DynamicPropertyFactory.getInstance()
            .getStringProperty("BlackPanther", " T'Chaka")
            .get();

        // THEN
        assertThat(myVar).isEqualsTo("T'Challa");
    }

    @After
    public void after() {
        ConfigurationManager.getConfigInstance().clear();
    }
}

public class AwesomeTest {
	@Rule
	public MockitoRule mockitoRule = MockitoJUnit.rule();
	@Mock
	private IncredibleService incredibleService;

	@InjectMocks
	private InvincibleService invincibleService;

	@Test
	public void test() {
		// some useless test
	}
}

JUnit5 : intérêt

  • API mise à jour pour prendre en compte Java 7 et plus
  • Découpage de la bibliothèque
  • pleins de petits trucs
    • @DisplayName
    • tests "dynamiques" => anciennement tests paramétrés
  • Blog d'Ippon
  • Blog de Zenika

JUnit5

Migrating from JUnit 4 to JUnit 5