Different types of dependency injection

This commit is contained in:
Ahmad Alsanie 2017-11-13 21:18:14 +02:00
parent 94f4dd1d77
commit b7b5543cf9
4 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,14 @@
package com.baeldung.ditypes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.baeldung.ditypes")
public class RegisterarConfig {
@Bean
public User user() {
return new User("Alice", 1);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.ditypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Registrar {
private User user;
@Autowired
public Registrar(User user) {
this.user = user;
}
public String register() {
return user.register();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.ditypes;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
private int id;
public User(String name, int id) {
this.id = id;
this.name = name;
}
public String register() {
return "User" + id + ": " + name + " is registered";
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.ditypes;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RegisterarConfig.class)
public class RegisterarTest {
@Autowired
private Registrar reg;
@Autowired
private User user;
@Test
public void givenAutowiredAnnotation_whenSetOnField_thenRegistrarIsInjected() {
assertNotNull(reg);
}
@Test
public void givenAutowiredAnnotation_whenSetOnField_thenUserIsInjected() {
assertEquals("User1: Alice is registered", user.register());
}
}