Skip to content

Commit b7b5543

Browse files
committed
Different types of dependency injection
1 parent 94f4dd1 commit b7b5543

4 files changed

Lines changed: 81 additions & 0 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.ditypes;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.ComponentScan;
5+
import org.springframework.context.annotation.Configuration;
6+
7+
@Configuration
8+
@ComponentScan("com.baeldung.ditypes")
9+
public class RegisterarConfig {
10+
@Bean
11+
public User user() {
12+
return new User("Alice", 1);
13+
}
14+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.ditypes;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.stereotype.Component;
5+
6+
@Component
7+
public class Registrar {
8+
private User user;
9+
10+
@Autowired
11+
public Registrar(User user) {
12+
this.user = user;
13+
}
14+
15+
public String register() {
16+
return user.register();
17+
}
18+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.ditypes;
2+
3+
import org.springframework.stereotype.Component;
4+
5+
@Component
6+
public class User {
7+
8+
private String name;
9+
private int id;
10+
11+
public User(String name, int id) {
12+
this.id = id;
13+
this.name = name;
14+
}
15+
16+
public String register() {
17+
return "User" + id + ": " + name + " is registered";
18+
}
19+
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.ditypes;
2+
3+
import static org.junit.Assert.*;
4+
import org.junit.Test;
5+
import org.junit.runner.RunWith;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.test.context.ContextConfiguration;
8+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
9+
10+
@RunWith(SpringJUnit4ClassRunner.class)
11+
@ContextConfiguration(classes = RegisterarConfig.class)
12+
public class RegisterarTest {
13+
14+
@Autowired
15+
private Registrar reg;
16+
17+
@Autowired
18+
private User user;
19+
20+
@Test
21+
public void givenAutowiredAnnotation_whenSetOnField_thenRegistrarIsInjected() {
22+
assertNotNull(reg);
23+
}
24+
25+
@Test
26+
public void givenAutowiredAnnotation_whenSetOnField_thenUserIsInjected() {
27+
assertEquals("User1: Alice is registered", user.register());
28+
}
29+
}

0 commit comments

Comments
 (0)